diff --git a/.directory b/.directory deleted file mode 100644 index bdd6b03..0000000 --- a/.directory +++ /dev/null @@ -1,6 +0,0 @@ -[Dolphin] -Timestamp=2015,11,22,12,41,21 -Version=3 - -[Settings] -HiddenFilesShown=true diff --git a/BaseAsset.php b/BaseAsset.php index 0206ace..0af23f6 100644 --- a/BaseAsset.php +++ b/BaseAsset.php @@ -1,9 +1,20 @@ + * @since 1.0 + */ class BaseAsset extends AssetBundle { public $css = [ @@ -15,7 +26,8 @@ class BaseAsset extends AssetBundle 'yii\bootstrap\BootstrapAsset', ]; - public function init(){ + public function init() + { parent::init(); $this->sourcePath = __DIR__ . '/assets'; } diff --git a/ConversationAsset.php b/ConversationAsset.php index 7156ade..37fe6fb 100644 --- a/ConversationAsset.php +++ b/ConversationAsset.php @@ -1,14 +1,19 @@ + * @since 1.0 */ class ConversationAsset extends AssetBundle { diff --git a/ConversationWidget.php b/ConversationWidget.php index 301da5b..a594861 100644 --- a/ConversationWidget.php +++ b/ConversationWidget.php @@ -1,12 +1,23 @@ + * @since 1.0 + */ class ConversationWidget extends ListView { public $user; @@ -20,10 +31,11 @@ class ConversationWidget extends ListView private $tag; - public function registerJs(){ + public function registerJs() + { $id = $this->options['id']; - if(!isset($this->clientOptions['selector'])){ - $this->clientOptions['selector'] = '.' . strstr($this->itemOptions['class'],' ',true); + if (!isset($this->clientOptions['selector'])) { + $this->clientOptions['selector'] = '.' . strstr($this->itemOptions['class'], ' ', true); } $options = Json::htmlEncode($this->clientOptions); $user = Json::htmlEncode($this->user); @@ -44,8 +56,8 @@ public function init() if (!isset($this->itemOptions['class'])) { $this->itemOptions['class'] = 'conv-item'; } - $this->tag = ArrayHelper::remove($this->options,'tag', 'div'); - echo Html::beginTag($this->tag,$this->options); + $this->tag = ArrayHelper::remove($this->options, 'tag', 'div'); + echo Html::beginTag($this->tag, $this->options); } @@ -73,16 +85,16 @@ public function renderItem($model, $key, $index) $options = $this->itemOptions; $tag = ArrayHelper::remove($options, 'tag', 'div'); if ($tag !== false) { - $options['data-key'] = is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : (string) $key; + $options['data-key'] = is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : (string)$key; $options['data-contact'] = $model['contact_id']; - if(isset($this->clientOptions['unreadCssClass'])){ + if (isset($this->clientOptions['unreadCssClass'])) { if ($model['new_messages'] > 0) { - Html::addCssClass($options,$this->clientOptions['unreadCssClass']); + Html::addCssClass($options, $this->clientOptions['unreadCssClass']); } } - if(isset($this->clientOptions['currentCssClass'])){ + if (isset($this->clientOptions['currentCssClass'])) { if ($model['contact_id'] == \Yii::$app->request->get('contactId')) { - Html::addCssClass($options,$this->clientOptions['currentCssClass']); + Html::addCssClass($options, $this->clientOptions['currentCssClass']); } } diff --git a/DataProvider.php b/DataProvider.php index f60b0e1..aa5c9bc 100644 --- a/DataProvider.php +++ b/DataProvider.php @@ -1,14 +1,11 @@ + * @since 1.0 + */ class DataProvider extends ActiveDataProvider implements Arrayable { use ArrayableTrait; @@ -33,10 +37,10 @@ public function init() } $request = \Yii::$app->request; - if($request->post('key')){ - if(!strcmp('history', $request->post('type'))){ + if ($request->post('key')) { + if (!strcmp('history', $request->post('type'))) { $this->query->andWhere(['<', 'id', $request->post('key')]); - }else{ + } else { $this->query->andWhere(['>', 'id', $request->post('key')]); } } @@ -48,7 +52,7 @@ public function init() protected function prepareTotalCount() { $query = clone $this->query; - return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db); + return (int)$query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db); } /** @@ -65,13 +69,13 @@ protected function prepareModels() $query->addOrderBy($sort->getOrders()); } - if($this->formatter !== null) { + if ($this->formatter !== null) { $models = []; - foreach($query->all($this->db) as $index => $model){ + foreach ($query->all($this->db) as $index => $model) { $models[$index] = call_user_func($this->formatter, $model); } return $models; - }else{ + } else { return $query->all($this->db); } diff --git a/DemoAsset.php b/DemoAsset.php index 8e2fa55..207dc3e 100644 --- a/DemoAsset.php +++ b/DemoAsset.php @@ -1,17 +1,19 @@ - * @since 2.0 + * Class DemoAsset + * @package bubasuma\simplechat + * + * @author Buba Suma + * @since 1.0 */ class DemoAsset extends AssetBundle { @@ -26,7 +28,8 @@ class DemoAsset extends AssetBundle 'bubasuma\simplechat\BaseAsset', ]; - public function init(){ + public function init() + { parent::init(); $this->sourcePath = __DIR__ . '/assets'; } diff --git a/MessageAsset.php b/MessageAsset.php index aca821e..d88aa93 100644 --- a/MessageAsset.php +++ b/MessageAsset.php @@ -1,14 +1,19 @@ + * @since 1.0 */ class MessageAsset extends AssetBundle { @@ -16,7 +21,8 @@ class MessageAsset extends AssetBundle 'js/messages.js', ]; - public function init(){ + public function init() + { parent::init(); $this->sourcePath = __DIR__ . '/assets'; } diff --git a/MessageWidget.php b/MessageWidget.php index d9897f6..e25904f 100644 --- a/MessageWidget.php +++ b/MessageWidget.php @@ -1,13 +1,24 @@ + * @since 1.0 + */ class MessageWidget extends ListView { /** @@ -26,7 +37,7 @@ class MessageWidget extends ListView public $formParams = []; - public $formOptions = ['method'=>'post']; + public $formOptions = ['method' => 'post']; public $clientOptions = []; @@ -37,21 +48,21 @@ class MessageWidget extends ListView public function renderForm() { - $action = ArrayHelper::remove($this->formOptions,'action','/message/' . $this->contact['id']); - $method = ArrayHelper::remove($this->formOptions,'method','post'); + $action = ArrayHelper::remove($this->formOptions, 'action', ''); + $method = ArrayHelper::remove($this->formOptions, 'method', 'post'); - if(!isset($this->formOptions['id'])){ + if (!isset($this->formOptions['id'])) { $this->formOptions['id'] = 'msg-form'; } - $content = Html::beginForm($action,$method,$this->formOptions); + $content = Html::beginForm($action, $method, $this->formOptions); if (is_string($this->formView)) { $content .= $this->getView()->render($this->formView, array_merge([ 'widget' => $this, ], $this->formParams)); } else { - $content .= call_user_func($this->formView,$this); + $content .= call_user_func($this->formView, $this); } $content .= Html::endForm(); @@ -60,10 +71,11 @@ public function renderForm() } - public function registerJs(){ + public function registerJs() + { $id = $this->options['id']; - if(!isset($this->clientOptions['selector'])){ - $this->clientOptions['selector'] = '.' . strstr($this->itemOptions['class'],' ',true); + if (!isset($this->clientOptions['selector'])) { + $this->clientOptions['selector'] = '.' . strstr($this->itemOptions['class'], ' ', true); } $this->clientOptions['form'] = '#' . $this->formOptions['id']; $options = Json::htmlEncode($this->clientOptions); @@ -86,8 +98,8 @@ public function init() if (!isset($this->itemOptions['class'])) { $this->itemOptions['class'] = 'msg-item'; } - $this->tag = ArrayHelper::remove($this->options,'tag', 'div'); - echo Html::beginTag($this->tag,$this->options); + $this->tag = ArrayHelper::remove($this->options, 'tag', 'div'); + echo Html::beginTag($this->tag, $this->options); } @@ -116,7 +128,7 @@ public function renderItem($model, $key, $index) $options = $this->itemOptions; $tag = ArrayHelper::remove($options, 'tag', 'div'); if ($tag !== false) { - $options['data-key'] = is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : (string) $key; + $options['data-key'] = is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : (string)$key; return Html::tag($tag, $content, $options); } else { @@ -153,6 +165,6 @@ public function getId() { $users = [$this->user['id'], $this->contact['id']]; sort($users); - return md5(implode('&',$users)); + return md5(implode('&', $users)); } } \ No newline at end of file diff --git a/Module.php b/Module.php index 9ddf30c..1ec91db 100644 --- a/Module.php +++ b/Module.php @@ -1,6 +1,11 @@ + * @author Buba Suma * @since 1.0 */ class Module extends \yii\base\Module implements BootstrapInterface @@ -48,6 +53,7 @@ class Module extends \yii\base\Module implements BootstrapInterface public $db = 'db'; public $controllerNamespace = 'bubasuma\simplechat\controllers'; + /** * Initializes simplechat module. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. @@ -77,7 +83,7 @@ public function bootstrap($app) 'PATCH conversation/read' => $this->id . '/default/mark-conversation-as-read', 'DELETE conversation' => $this->id . '/default/delete-conversation', ], false); - }elseif ($app instanceof \yii\console\Application) { + } elseif ($app instanceof \yii\console\Application) { $app->controllerMap[$this->id] = [ 'class' => 'bubasuma\simplechat\console\DemoController', 'module' => $this, diff --git a/assets/js/chat.js b/assets/js/chat.js index 2d8e47c..2c37c26 100644 --- a/assets/js/chat.js +++ b/assets/js/chat.js @@ -1,3 +1,14 @@ +/** + * yii2-simplechat demo javascript. + * + * This is the JavaScript used by the demo page. + * + * @link https://github.com/bubasuma/yii2-simplechat + * @copyright Copyright (c) 2015 bubasuma + * @license http://opensource.org/licenses/BSD-3-Clause + * @author Buba Suma + * @since 1.0 + */ (function ($) { var msgWrapper = document.getElementById('msg-wrap'); var convWrapper = document.getElementById('conv-wrap'); diff --git a/assets/js/conversations.js b/assets/js/conversations.js index 0c1af1d..5d591a8 100644 --- a/assets/js/conversations.js +++ b/assets/js/conversations.js @@ -1,3 +1,14 @@ +/** + * yii2-simplechat conversations widget. + * + * This is the JavaScript widget used by the bubasuma\simplechat\ConversationWidget widget. + * + * @link https://github.com/bubasuma/yii2-simplechat + * @copyright Copyright (c) 2015 bubasuma + * @license http://opensource.org/licenses/BSD-3-Clause + * @author Buba Suma + * @since 1.0 + */ (function ($) { $.fn.simpleChatConversations = function (method) { if (methods[method]) { diff --git a/assets/js/messages.js b/assets/js/messages.js index ea75751..0c4887c 100644 --- a/assets/js/messages.js +++ b/assets/js/messages.js @@ -1,3 +1,14 @@ +/** + * yii2-simplechat messages widget. + * + * This is the JavaScript widget used by the bubasuma\simplechat\MessageWidget widget. + * + * @link https://github.com/bubasuma/yii2-simplechat + * @copyright Copyright (c) 2015 bubasuma + * @license http://opensource.org/licenses/BSD-3-Clause + * @author Buba Suma + * @since 1.0 + */ (function ($) { $.fn.simpleChatMessages = function (method) { if (methods[method]) { diff --git a/assets/temp.js b/assets/temp.js deleted file mode 100644 index 11bd163..0000000 --- a/assets/temp.js +++ /dev/null @@ -1,261 +0,0 @@ -/** - * @file chat.js - * - * Provides information about timezone - * @author Buba Suma - * - */ - -var Message = { - - init: function (cid,selectors,options) { - var self = this; - - self.cid = cid; - self.isLive = false; - self.form = $(selectors.form); - self.container = $(selectors.container); - self.selector = selectors.message; - self.options = options || {}; - self.options.loadUrl = options.loadUrl || ''; - self.loaded = false; - self.loading = false; - self.cache = {}; - - self.form.on('submit', function () { - self.send(); - return false; - }); - - }, - - live: function (listenUrl) { - - var self = this; - - self.isLive = true; - - self.socket = io(listenUrl); - - self.socket.on('connect', function(){ - - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'connect'); - } - - self.socket.emit('load', {cid: self.cid}); - }); - - self.socket.on('peopleInChat', function(data){ - - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'peopleInChat',data); - } - - if(data.number < 2) { - console.log('participate'); - self.socket.emit('participate', {user: self.options.data.user, cid: self.cid}); - } - - }); - - self.socket.on('ready', function(data){ - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'ready',data); - } - }); - - self.socket.on('leave',function(data){ - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'leave',data); - } - }); - - self.socket.on('tooMany', function(data){ - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'tooMany',data); - } - }); - - self.socket.on('receive', function(data){ - console.log('receive'); - if( self.options.liveCallback != undefined){ - self.options.liveCallback(self,'receive',data.message); - } - }); - }, - - firstMessage: function () { - var self = this; - return self.container.find(self.selector + ':first-child'); - }, - - lastMessage: function () { - var self = this; - return self.container.find(self.selector + ':last-child'); - }, - - send: function () { - var self = this; - var datatype = self.form.attr('data-type'); - $.ajax({ - url: self.form.attr('action'), - type: self.form.attr('method'), - dataType: datatype == undefined ? 'json':datatype, - data: self.form.serialize(), - beforeSend: function (xhr,settings) { - return self.sendBeforeSendCallback(xhr,settings); - }, - complete: function (xhr,textStatus) { - self.sendCompleteCallback(xhr,textStatus); - }, - success: function (data) { - self.sendSuccessCallback(data); - }, - error: function (xhr,textStatus,errorThrown) { - self.sendErrorCallback(xhr,textStatus,errorThrown); - } - }); - }, - - load: function (type,datatype) { - var self = this; - if(self.loading == false && self.loaded == false ) { - self.loading = true; - $.ajax({ - url: self.options.loadUrl, - type: type == undefined ? 'post' : type, - dataType: datatype == undefined ? 'json' : datatype, - data: { - history: parseInt(self.firstMessage().data('utctime')) - }, - beforeSend: function (xhr, settings) { - return self.loadBeforeSendCallback(xhr, settings); - }, - complete: function (xhr, textStatus) { - self.loading = false; - self.loadCompleteCallback(xhr, textStatus); - }, - success: function (data) { - if (data.length == 0) { - self.loaded = true; - } else { - self.loadSuccessCallback(data); - } - }, - error: function (xhr, textStatus, errorThrown) { - self.loadErrorCallback(xhr, textStatus, errorThrown); - } - }); - } - }, - - append: function (data) { - var self = this; - if(typeof(data) != 'string'){ - self.container.append(self.tmpl(self.options.templateId,data)); - }else{ - self.container.append(data); - } - }, - - prepend: function (data) { - var self = this; - if(typeof(data) != 'string'){ - self.container.prepend(self.tmpl(self.options.templateId,data)); - }else{ - self.container.prepend(data); - } - }, - - sendCompleteCallback: function (xhr,textStatus) { - var self = this; - if( self.options.sendCompleteCallback != undefined){ - self.options.sendCompleteCallback(self,xhr,textStatus); - } - }, - - sendBeforeSendCallback: function (xhr,settings) { - var self = this; - if( self.options.sendBeforeSendCallback != undefined){ - return self.options.sendBeforeSendCallback(self,xhr,settings); - } - return true; - - }, - - sendSuccessCallback: function (data) { - var self = this; - - if( self.options.sendSuccessCallback != undefined){ - self.options.sendSuccessCallback(self,data); - } - - if(self.isLive === true){ - console.log("send", data); - self.socket.emit('send', {message: data, cid: self.cid}); - } - }, - - sendErrorCallback: function (textStatus,errorThrown) { - var self = this; - if( self.options.sendErrorCallback != undefined){ - self.options.sendErrorCallback(self,xhr,textStatus,errorThrown); - } - }, - - loadCompleteCallback: function (xhr,textStatus) { - var self = this; - if( self.options.loadCompleteCallback != undefined){ - self.options.loadCompleteCallback(self,xhr,textStatus); - } - }, - - loadBeforeSendCallback: function (xhr,settings) { - var self = this; - if( self.options.loadBeforeSendCallback != undefined){ - return self.options.loadBeforeSendCallback(self,xhr,settings); - } - return true; - }, - - loadSuccessCallback: function (data) { - var self = this; - if( self.options.loadSuccessCallback != undefined){ - self.options.loadSuccessCallback(self,data); - } - }, - - loadErrorCallback: function (textStatus,errorThrown) { - var self = this; - if( self.options.loadErrorCallback != undefined){ - self.options.loadErrorCallback(self,xhr,textStatus,errorThrown); - } - }, - - tmpl : function (str, data){ - var self = this; - - var fn = !/\W/.test(str) ? - self.cache[str] = self.cache[str] || self.tmpl(document.getElementById(str).innerHTML) : - - new Function("obj", - "var p=[],print=function(){p.push.apply(p,arguments);};" + - - "with(obj){p.push('" + - - str - .replace(/[\r\t\n]/g, " ") - .split("<%").join("\t") - .replace(/((^|%>)[^\t]*)'/g, "$1\r") - .replace(/\t=(.*?)%>/g, "',$1,'") - .split("\t").join("');") - .split("%>").join("p.push('") - .split("\r").join("\\'") - + "');}return p.join('');"); - - return data ? fn( data ) : fn; - } - - -}; diff --git a/console/ConsoleController.php b/console/ConsoleController.php deleted file mode 100644 index 76e5d89..0000000 --- a/console/ConsoleController.php +++ /dev/null @@ -1,78 +0,0 @@ -migrationPath); - $this->migrationPath = $path; - $this->module->db->tablePrefix = $this->module->id.'_'; - $this->stdout("Yii2 SimpleChat Demo\n\n", Console::BOLD); - return true; - } else { - return false; - } - } - - /** - * Shows help - */ - public function actionIndex() - { - $this->run('/help', ['simplechat']); - } - - /** - * Apply migration for demo chat by creating tables and data - */ - public function actionStart() - { - $this->module->runAction("migrate",['migrationPath' => $this->migrationPath]); - } - - /** - * Clear database from demo data and tables - */ - public function actionStop() - { - $this->module->runAction("migrate/down",['migrationPath' => $this->migrationPath]); - } - - /** - * @inheritdoc - */ - public function getUniqueID() - { - return $this->id; - } -} \ No newline at end of file diff --git a/console/DemoController.php b/console/DemoController.php index fa2466d..e081f4a 100644 --- a/console/DemoController.php +++ b/console/DemoController.php @@ -1,4 +1,9 @@ + * @since 1.0 */ class DemoController extends Controller { @@ -34,7 +44,7 @@ class DemoController extends Controller public function beforeAction($action) { if (parent::beforeAction($action)) { - if(!strcmp($action->id, 'start') || !strcmp($action->id, 'stop')){ + if (!strcmp($action->id, 'start') || !strcmp($action->id, 'stop')) { $this->module->initDemo(); $this->module->controllerMap['migrate'] = [ 'class' => 'bubasuma\simplechat\console\MigrateController', diff --git a/console/MigrateController.php b/console/MigrateController.php index f48ccd0..2d21a71 100644 --- a/console/MigrateController.php +++ b/console/MigrateController.php @@ -1,19 +1,23 @@ + * @since 1.0 + */ class MigrateController extends \yii\console\controllers\MigrateController { - /** * Creates the migration history table. */ @@ -30,10 +34,10 @@ protected function deleteMigrationHistoryTable() */ public function actionDown($limit = 'all') { - $ret = parent::actionDown('all'); + $ret = parent::actionDown('all'); $query = new Query; $query->from($this->migrationTable); - if(1 == $query->count()){ + if (1 == $query->count()) { $this->deleteMigrationHistoryTable(); } return $ret; diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 6e89e01..5a48674 100644 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -1,5 +1,9 @@ + * @since 1.0 + */ class DefaultController extends Controller { public $layout = 'main'; @@ -47,8 +58,8 @@ public function behaviors() [ 'class' => 'yii\filters\VerbFilter', 'actions' => [ - 'index' => ['get'], - 'messages' => ['post'], + 'index' => ['get'], + 'messages' => ['post'], 'create-message' => ['post', 'put'], 'conversations' => ['post'], 'delete-conversation' => ['delete'], @@ -70,7 +81,7 @@ public function actionConversations() $callable = [$this->modelClass, 'loadConversations']; $formatter = [$this, 'formatConversation']; $limit = \Yii::$app->request->post('limit'); - return call_user_func($callable, $userId, $formatter, $limit); + return call_user_func($callable, $userId, $formatter, $limit); } public function actionMessages($contactId) @@ -82,32 +93,37 @@ public function actionMessages($contactId) return call_user_func($callable, $userId, $contactId, $formatter, $limit); } - public function actionCreateMessage($contactId){ + public function actionCreateMessage($contactId) + { $userId = $this->user->id; - if($userId == $contactId){ + if ($userId == $contactId) { throw new ForbiddenHttpException('You attempt to send message to yourself'); } $text = \Yii::$app->request->post('text'); - return call_user_func([$this->modelClass,'create'], $userId, $contactId, $text); + return call_user_func([$this->modelClass, 'create'], $userId, $contactId, $text); } - public function actionDeleteMessage($id){ + public function actionDeleteMessage($id) + { throw new NotSupportedException(get_class($this) . ' does not support actionDeleteMessage().'); } - public function actionDeleteConversation($contactId){ + public function actionDeleteConversation($contactId) + { $userId = $this->user->id; $callable = [$this->modelClass, 'deleteConversation']; return call_user_func($callable, $userId, $contactId); } - public function actionMarkConversationAsRead($contactId){ + public function actionMarkConversationAsRead($contactId) + { $userId = $this->user->id; $callable = [$this->modelClass, 'markConversationAsRead']; return call_user_func($callable, $userId, $contactId); } - public function actionMarkConversationAsUnread($contactId){ + public function actionMarkConversationAsUnread($contactId) + { $userId = $this->user->id; $callable = [$this->modelClass, 'markConversationAsUnRead']; return call_user_func($callable, $userId, $contactId); @@ -117,7 +133,8 @@ public function actionMarkConversationAsUnread($contactId){ * @param array|Model $model * @return array */ - public function formatMessage($model){ + public function formatMessage($model) + { return $model; } @@ -125,8 +142,9 @@ public function formatMessage($model){ * @param array $model * @return array */ - public function formatConversation($model){ - $model['new_messages'] = ArrayHelper::getValue($model,'newMessages.count',0); + public function formatConversation($model) + { + $model['new_messages'] = ArrayHelper::getValue($model, 'newMessages.count', 0); ArrayHelper::remove($model, 'newMessages'); return $model; } diff --git a/controllers/DemoController.php b/controllers/DemoController.php index 6919802..3a2bdc7 100644 --- a/controllers/DemoController.php +++ b/controllers/DemoController.php @@ -1,5 +1,9 @@ + * @since 1.0 + */ class DemoController extends DefaultController { /** @@ -36,7 +47,7 @@ public function actionIndex($contactId) */ $user = $this->user; $contact = User::findOne(['id' => $contactId]); - if(empty($contact)){ + if (empty($contact)) { throw new NotFoundHttpException(); } @@ -51,15 +62,15 @@ public function actionIndex($contactId) $users = []; - foreach(User::find()->with('profile')->all() as $userItem){ + foreach (User::find()->with('profile')->all() as $userItem) { $users[] = [ 'label' => $userItem->fullName, - 'url' =>'/messages?userId=' . $userItem->id . '&contactId=' . $contact->id, + 'url' => '/messages?userId=' . $userItem->id . '&contactId=' . $contact->id, 'options' => ['class' => $userItem->id == $contact->id || $userItem->id == $user->id ? 'disabled' : ''] ]; } - return $this->render('index',compact('conversationDataProvider','messageDataProvider', 'users','user','contact')); + return $this->render('index', compact('conversationDataProvider', 'messageDataProvider', 'users', 'user', 'contact')); } @@ -76,7 +87,7 @@ public function formatConversation($model) { $model = parent::formatConversation($model); $model['date'] = DateHelper::formatConversationDate($model['created_at']); - $model['text'] = StringHelper::truncate($model['text'],20); + $model['text'] = StringHelper::truncate($model['text'], 20); return $model; } diff --git a/db/ConversationQuery.php b/db/ConversationQuery.php index fe29eb9..b0f4372 100644 --- a/db/ConversationQuery.php +++ b/db/ConversationQuery.php @@ -1,18 +1,22 @@ + * @since 1.0 + */ class ConversationQuery extends ActiveQuery { public $userId; @@ -67,7 +71,7 @@ public function populate($rows) if ($this->indexBy === null) { $models = $rows; - }else{ + } else { foreach ($rows as $row) { if (is_string($this->indexBy)) { $key = $row[$this->indexBy]; diff --git a/db/MessageQuery.php b/db/MessageQuery.php index 344d63c..bc7e7c5 100644 --- a/db/MessageQuery.php +++ b/db/MessageQuery.php @@ -1,17 +1,21 @@ + * @since 1.0 + */ class MessageQuery extends ActiveQuery { public $userId; @@ -23,7 +27,7 @@ public function init() /* @var $modelClass ActiveRecord */ $modelClass = $this->modelClass; $tableName = $modelClass::tableName(); - $this->select(['m.id','m.text', 'm.created_at', 'm.is_new', 'm.sender_id']) + $this->select(['m.id', 'm.text', 'm.created_at', 'm.is_new', 'm.sender_id']) ->from(['m' => $tableName]) ->where( ['or', diff --git a/db/Model.php b/db/Model.php index 92e9e37..f853135 100644 --- a/db/Model.php +++ b/db/Model.php @@ -1,6 +1,11 @@ + * @since 1.0 + * */ class Model extends ActiveRecord { public static function tableName() { - return Migration::TABLE_MESSAGE; + return Migration::TABLE_MESSAGE; } /** @@ -36,12 +44,13 @@ public static function tableName() public function rules() { return [ - [['sender_id', 'receiver_id', 'text', 'created_at'], 'required', 'on'=>'create'] + [['sender_id', 'receiver_id', 'text', 'created_at'], 'required', 'on' => 'create'] ]; } - public function getNewMessages(){ - return $this->hasOne(static::className(),['sender_id' => 'contact_id']) + public function getNewMessages() + { + return $this->hasOne(static::className(), ['sender_id' => 'contact_id']) ->where(['is_new' => 1]) ->groupBy('sender_id'); } @@ -54,7 +63,7 @@ public function getNewMessages(){ */ public static function conversations($userId) { - /**@var ConversationQuery $query**/ + /**@var ConversationQuery $query * */ $query = \Yii::createObject(ConversationQuery::className(), [ get_called_class(), @@ -62,9 +71,9 @@ public static function conversations($userId) ] ); return $query->with([ - 'newMessages' => function($msg) use ($userId) { - /**@var $msg ConversationQuery **/ - $msg->andOnCondition(['receiver_id' => $userId])->select(['sender_id','COUNT(*) AS count']); + 'newMessages' => function ($msg) use ($userId) { + /**@var $msg ConversationQuery * */ + $msg->andOnCondition(['receiver_id' => $userId])->select(['sender_id', 'COUNT(*) AS count']); } ]); } @@ -77,7 +86,8 @@ public static function conversations($userId) * @param int $limit * @return DataProvider */ - public static function loadConversations($userId, $formatter, $limit){ + public static function loadConversations($userId, $formatter, $limit) + { return new DataProvider([ 'query' => static::conversations($userId), 'formatter' => $formatter, @@ -129,8 +139,9 @@ public static function loadMessages($userId, $contactId, $formatter, $limit) * @param string $contactId * @return array the number of rows updated */ - public static function deleteConversation($userId, $contactId){ - $count = static::updateAll( + public static function deleteConversation($userId, $contactId) + { + $count = static::updateAll( [ 'is_deleted_by_sender' => new Expression('IF([[sender_id]] =:userId, 1, is_deleted_by_sender)'), 'is_deleted_by_receiver' => new Expression('IF([[receiver_id]] =:userId, 1, is_deleted_by_receiver)') @@ -181,24 +192,24 @@ public static function markConversationAsUnread($userId, $contactId) ->orderBy(['id' => SORT_DESC]) ->limit(1) ->one(); - $count = 0; - if($last_received_message){ + $count = 0; + if ($last_received_message) { $last_received_message->is_new = 1; - $count = intval($last_received_message->update()); + $count = intval($last_received_message->update()); } return compact('count'); } - /** * @param string $userId * @param string $contactId * @param string $text * @return array|bool returns true on success or errors if validation fails */ - public static function create($userId, $contactId, $text){ - $instance = new static(['scenario'=>'create']); + public static function create($userId, $contactId, $text) + { + $instance = new static(['scenario' => 'create']); $instance->created_at = new Expression('UTC_TIMESTAMP()'); $instance->sender_id = $userId; $instance->receiver_id = $contactId; diff --git a/db/demo/Message.php b/db/demo/Message.php index 1f74f91..5bf4ff2 100644 --- a/db/demo/Message.php +++ b/db/demo/Message.php @@ -1,12 +1,12 @@ + * @since 1.0 */ class Message extends \bubasuma\simplechat\db\Model { public function getContact() { - return $this->hasOne(User::className(),['id'=>'contact_id']); + return $this->hasOne(User::className(), ['id' => 'contact_id']); } /** @@ -29,14 +32,14 @@ public function getContact() public static function conversations($userId) { return parent::conversations($userId)->with([ - 'contact' => function($contact){ - /**@var $contact ActiveQuery **/ + 'contact' => function ($contact) { + /**@var $contact ActiveQuery * */ $contact->with([ - 'profile' => function($advanced){ - /**@var $advanced ActiveQuery **/ - $advanced->select(['id','CONCAT_WS(\' \', first_name, last_name) AS full_name', 'avatar']); + 'profile' => function ($advanced) { + /**@var $advanced ActiveQuery * */ + $advanced->select(['id', 'CONCAT_WS(\' \', first_name, last_name) AS full_name', 'avatar']); }, - ])->select(['id','email']); + ])->select(['id', 'email']); } ]); } diff --git a/db/demo/User.php b/db/demo/User.php index 972e4a4..37f7e6d 100644 --- a/db/demo/User.php +++ b/db/demo/User.php @@ -1,9 +1,8 @@ + * @since 1.0 + * */ class User extends ActiveRecord { @@ -56,12 +58,12 @@ public function beforeSave($insert) public function getProfile() { - return $this->hasOne(UserProfile::className(),['id'=>'id']); + return $this->hasOne(UserProfile::className(), ['id' => 'id']); } public function getFullName() { - return $this->profile->first_name. ' '.$this->profile->last_name; + return $this->profile->first_name . ' ' . $this->profile->last_name; } diff --git a/db/demo/UserProfile.php b/db/demo/UserProfile.php index b666194..818ac73 100644 --- a/db/demo/UserProfile.php +++ b/db/demo/UserProfile.php @@ -1,14 +1,11 @@ + * @since 1.0 */ class UserProfile extends ActiveRecord { diff --git a/helpers/DateHelper.php b/helpers/DateHelper.php index 0baf59b..569b4ad 100644 --- a/helpers/DateHelper.php +++ b/helpers/DateHelper.php @@ -1,45 +1,53 @@ + * @since 1.0 */ class DateHelper { public static function formatMessageDate($value) { - $today = date_create()->setTime(0,0,0); - $date = date_create($value)->setTime(0,0,0); - if($today == $date) { + $today = date_create()->setTime(0, 0, 0); + $date = date_create($value)->setTime(0, 0, 0); + if ($today == $date) { $label = 'Today'; - }else if($today->getTimestamp() - $date->getTimestamp() == 24 * 60 * 60) { + } else if ($today->getTimestamp() - $date->getTimestamp() == 24 * 60 * 60) { $label = 'Yesterday'; - }else if($today->format('W') == $date->format('W') && $today->format('Y') == $date->format('Y')) { - $label = \Yii::$app->formatter->asDate($value,'php:l'); - }else if($today->format('Y') == $date->format('Y')) { - $label = \Yii::$app->formatter->asDate($value,'php:d F'); - }else { - $label = \Yii::$app->formatter->asDate($value,'medium'); + } else if ($today->format('W') == $date->format('W') && $today->format('Y') == $date->format('Y')) { + $label = \Yii::$app->formatter->asDate($value, 'php:l'); + } else if ($today->format('Y') == $date->format('Y')) { + $label = \Yii::$app->formatter->asDate($value, 'php:d F'); + } else { + $label = \Yii::$app->formatter->asDate($value, 'medium'); } - $formatted = \Yii::$app->formatter->asTime($value,'short'); + $formatted = \Yii::$app->formatter->asTime($value, 'short'); return [$label, $formatted]; } public static function formatConversationDate($value) { - $today = date_create()->setTime(0,0,0); - $date = date_create($value)->setTime(0,0,0); - if($today == $date) { - $formatted = \Yii::$app->formatter->asTime($value,'short'); - }else if($today->getTimestamp() - $date->getTimestamp() == 24 * 60 * 60) { + $today = date_create()->setTime(0, 0, 0); + $date = date_create($value)->setTime(0, 0, 0); + if ($today == $date) { + $formatted = \Yii::$app->formatter->asTime($value, 'short'); + } else if ($today->getTimestamp() - $date->getTimestamp() == 24 * 60 * 60) { $formatted = 'Yesterday'; - }else if($today->format('W') == $date->format('W') && $today->format('Y') == $date->format('Y')) { - $formatted = \Yii::$app->formatter->asDate($value,'php:l'); - }else if($today->format('Y') == $date->format('Y')) { - $formatted = \Yii::$app->formatter->asDate($value,'php:d F'); - }else { - $formatted = \Yii::$app->formatter->asDate($value,'medium'); + } else if ($today->format('W') == $date->format('W') && $today->format('Y') == $date->format('Y')) { + $formatted = \Yii::$app->formatter->asDate($value, 'php:l'); + } else if ($today->format('Y') == $date->format('Y')) { + $formatted = \Yii::$app->formatter->asDate($value, 'php:d F'); + } else { + $formatted = \Yii::$app->formatter->asDate($value, 'medium'); } return $formatted; } diff --git a/migrations/Migration.php b/migrations/Migration.php index b5fdc5b..eac5e5a 100755 --- a/migrations/Migration.php +++ b/migrations/Migration.php @@ -1,18 +1,27 @@ + * @since 1.0 */ -class Migration extends \yii\db\Migration { +class Migration extends \yii\db\Migration +{ const TABLE_USER = '{{%user}}'; const TABLE_USER_PROFILE = '{{%user_profile}}'; const TABLE_MESSAGE = '{{%message}}'; - public function getTableOptions(){ + public function getTableOptions() + { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; diff --git a/migrations/data/messages.php b/migrations/data/messages.php index 8355296..ac9a650 100644 --- a/migrations/data/messages.php +++ b/migrations/data/messages.php @@ -1,4 +1,9 @@ 'johnny-deep@gmail.com', diff --git a/migrations/m151121_105223_user_table.php b/migrations/m151121_105223_user_table.php index 9c99896..4cd3881 100644 --- a/migrations/m151121_105223_user_table.php +++ b/migrations/m151121_105223_user_table.php @@ -1,6 +1,17 @@ + * @since 1.0 + */ class m151121_105223_user_table extends Migration { public function up() @@ -11,7 +22,7 @@ public function up() 'created_at' => 'DATETIME NOT NULL', ], $this->tableOptions); $tableName = $this->db->getSchema()->getRawTableName(self::TABLE_USER); - $this->createIndex("idx-$tableName-email", self::TABLE_USER, 'email',true); + $this->createIndex("idx-$tableName-email", self::TABLE_USER, 'email', true); } public function down() diff --git a/migrations/m151121_105406_user_profile_table.php b/migrations/m151121_105406_user_profile_table.php index f38d98d..edda606 100644 --- a/migrations/m151121_105406_user_profile_table.php +++ b/migrations/m151121_105406_user_profile_table.php @@ -1,7 +1,17 @@ + * @since 1.0 + */ class m151121_105406_user_profile_table extends Migration { public function up() @@ -14,7 +24,7 @@ public function up() 'avatar' => 'VARCHAR(63) DEFAULT NULL', ], $this->tableOptions); $tableName = $this->db->getSchema()->getRawTableName(self::TABLE_USER_PROFILE); - $this->addForeignKey("fk-$tableName-id",self::TABLE_USER_PROFILE,'id',self::TABLE_USER,'id','CASCADE','CASCADE'); + $this->addForeignKey("fk-$tableName-id", self::TABLE_USER_PROFILE, 'id', self::TABLE_USER, 'id', 'CASCADE', 'CASCADE'); } public function down() diff --git a/migrations/m151121_105453_message_table.php b/migrations/m151121_105453_message_table.php index 465ba03..4d8560d 100644 --- a/migrations/m151121_105453_message_table.php +++ b/migrations/m151121_105453_message_table.php @@ -1,7 +1,17 @@ + * @since 1.0 + */ class m151121_105453_message_table extends Migration { public function up() @@ -17,8 +27,8 @@ public function up() 'created_at' => 'DATETIME NOT NULL', ], $this->tableOptions); $tableName = $this->db->getSchema()->getRawTableName(self::TABLE_MESSAGE); - $this->addForeignKey("fk-$tableName-sender_id",self::TABLE_MESSAGE,'sender_id',self::TABLE_USER,'id','NO ACTION','CASCADE'); - $this->addForeignKey("fk-$tableName-receiver_id",self::TABLE_MESSAGE,'receiver_id',self::TABLE_USER,'id','NO ACTION','CASCADE'); + $this->addForeignKey("fk-$tableName-sender_id", self::TABLE_MESSAGE, 'sender_id', self::TABLE_USER, 'id', 'NO ACTION', 'CASCADE'); + $this->addForeignKey("fk-$tableName-receiver_id", self::TABLE_MESSAGE, 'receiver_id', self::TABLE_USER, 'id', 'NO ACTION', 'CASCADE'); } public function down() diff --git a/migrations/m151121_105654_user_data.php b/migrations/m151121_105654_user_data.php index 77d22e2..cb9b1a2 100644 --- a/migrations/m151121_105654_user_data.php +++ b/migrations/m151121_105654_user_data.php @@ -1,29 +1,38 @@ + * @since 1.0 + */ class m151121_105654_user_data extends Migration { public function up() { - $data = require(__DIR__.'/data/users.php'); - try{ - foreach($data as $item){ + $data = require(__DIR__ . '/data/users.php'); + try { + foreach ($data as $item) { $user = new \bubasuma\simplechat\db\demo\User(); $user->setAttributes($item); - if($user->save()){ + if ($user->save()) { $profile = new \bubasuma\simplechat\db\demo\UserProfile(); $profile->setAttributes($item); $profile->id = $user->id; - if(!$profile->save()){ + if (!$profile->save()) { $user->delete(); } } } return true; - }catch (\yii\base\Exception $e){ + } catch (\yii\base\Exception $e) { return false; } diff --git a/migrations/m151121_105707_message_data.php b/migrations/m151121_105707_message_data.php index b0c92e0..0dfee2d 100644 --- a/migrations/m151121_105707_message_data.php +++ b/migrations/m151121_105707_message_data.php @@ -1,29 +1,39 @@ + * @since 1.0 + */ class m151121_105707_message_data extends Migration { public function up() { $users = \bubasuma\simplechat\db\demo\User::find()->select(['id'])->asArray()->all(); - $data = require(__DIR__.'/data/messages.php'); + $data = require(__DIR__ . '/data/messages.php'); $count = count($data); $messages = []; try { - for ($i=1; $i <= 10000; $i++) { + for ($i = 1; $i <= 10000; $i++) { shuffle($users); $sender = $users[0]; $receiver = $users[1]; $messages[] = [ 'sender_id' => $sender['id'], 'receiver_id' => $receiver['id'], - 'created_at' => (new \DateTime())->sub(new \DateInterval('P' . (mt_rand() % 500) . 'DT'.(mt_rand() % 86400).'S'))->getTimestamp(), - 'text' => $data[mt_rand(0,$count-1)], + 'created_at' => (new \DateTime())->sub(new \DateInterval('P' . (mt_rand() % 500) . 'DT' . (mt_rand() % 86400) . 'S'))->getTimestamp(), + 'text' => $data[mt_rand(0, $count - 1)], ]; } - ArrayHelper::multisort($messages,'created_at',SORT_ASC, SORT_NUMERIC); + ArrayHelper::multisort($messages, 'created_at', SORT_ASC, SORT_NUMERIC); foreach ($messages as $message) { $new = new \bubasuma\simplechat\db\demo\Message(); $new->sender_id = $message['sender_id']; diff --git a/views/default/index.php b/views/default/index.php index 12d910f..5434b33 100644 --- a/views/default/index.php +++ b/views/default/index.php @@ -1,6 +1,6 @@ You have successfully installed Yii2-SimpleChat.

-

Get started with Demo

+

Get started with + Demo

diff --git a/views/demo/conversation.php b/views/demo/conversation.php index 751a344..b605cc8 100644 --- a/views/demo/conversation.php +++ b/views/demo/conversation.php @@ -1,6 +1,7 @@ itemOptions['data-contact-info'] = $model['contact']; ?> - 64x64 + 64x64
- + -
- ':''?> - 0 ? $model['new_messages'] : ''?> +
+ ' : '' ?> + 0 ? $model['new_messages'] : '' ?>
diff --git a/views/demo/index.php b/views/demo/index.php index 2e6909b..359b03c 100644 --- a/views/demo/index.php +++ b/views/demo/index.php @@ -4,12 +4,12 @@ use bubasuma\simplechat\DemoAsset; /** - *@var $user User - *@var $contact User - *@var array $users - *@var $messageDataProvider \yii\data\ActiveDataProvider - *@var $conversationDataProvider \yii\data\ActiveDataProvider - *@var $this \yii\web\View + * @var $user User + * @var $contact User + * @var array $users + * @var $messageDataProvider \yii\data\ActiveDataProvider + * @var $conversationDataProvider \yii\data\ActiveDataProvider + * @var $this \yii\web\View */ $asset = DemoAsset::register($this); $this->params['user'] = $user; @@ -22,8 +22,8 @@ $conversation = \bubasuma\simplechat\ConversationWidget::begin([ 'dataProvider' => $conversationDataProvider, - 'options' => ['class'=>'conversation-wrap col-lg-3', 'id'=>'conv-wrap'], - 'itemOptions' => ['class'=>'media conversation'], + 'options' => ['class' => 'conversation-wrap col-lg-3', 'id' => 'conv-wrap'], + 'itemOptions' => ['class' => 'media conversation'], 'user' => [ 'id' => $user->id, 'profile' => [ @@ -37,7 +37,7 @@ 'unreadUrl' => '/conversation/unread?userId=' . $user->id, 'template' => '#conv-tmpl', 'currentCssClass' => 'current', - 'unreadCssClass'=>'unread', + 'unreadCssClass' => 'unread', 'baseUrl' => $asset->baseUrl ] ]); @@ -45,7 +45,7 @@ renderItems() ?> $contact->profile->avatar, ], ], - 'options' => ['class'=>'message-wrap col-lg-8', 'id'=>'messages'], - 'itemOptions' => ['class'=>'media msg'], + 'options' => ['class' => 'message-wrap col-lg-8', 'id' => 'messages'], + 'itemOptions' => ['class' => 'media msg'], 'formOptions' => [ 'action' => '/message?userId=' . $user->id, - 'method'=>'post' + 'method' => 'post' ], 'clientOptions' => [ - 'loadUrl' => '/messages?userId='.$user->id, + 'loadUrl' => '/messages?userId=' . $user->id, 'container' => '#msg-wrap', 'template' => '#msg-tmpl', 'baseUrl' => $asset->baseUrl, @@ -84,7 +84,7 @@ ?>
renderItems();?> dataProvider->getKeys(); $rows = []; $when = false; - foreach (array_reverse($models,true) as $index => $model) { - if(strcmp($when, $model['when'])){ + foreach (array_reverse($models, true) as $index => $model) { + if (strcmp($when, $model['when'])) { $when = $model['when']; - $rows[] = \yii\bootstrap\Html::tag('div',"$when",['class'=>'alert alert-info msg-date']); + $rows[] = \yii\bootstrap\Html::tag('div', "$when", ['class' => 'alert alert-info msg-date']); } $rows[] = $message->renderItem($model, $keys[$index], $index); } @@ -104,17 +104,18 @@
- renderForm();?> + renderForm(); ?>
- + diff --git a/views/demo/message.php b/views/demo/message.php index 4848c3e..e108691 100644 --- a/views/demo/message.php +++ b/views/demo/message.php @@ -13,10 +13,11 @@ ?> - 64x64 + 64x64
- -
- + +
+
diff --git a/views/layouts/main.php b/views/layouts/main.php index 0071f5d..08022bc 100755 --- a/views/layouts/main.php +++ b/views/layouts/main.php @@ -32,9 +32,9 @@ $menuItems = []; - if(isset($this->params['user']) && isset($this->params['users'])){ + if (isset($this->params['user']) && isset($this->params['users'])) { $menuItems[] = [ - 'label' => 'Hi, '. $this->params['user']['fullName'], + 'label' => 'Hi, ' . $this->params['user']['fullName'], 'items' => \yii\helpers\ArrayHelper::merge( [ ['label' => 'Log in as'] @@ -59,6 +59,7 @@