Hash with arrays - get array element - ruby

I get hash that contains user role, controller name and list of the controller actions this role can access to.
access = {
'admin' => [ 'users' => ['edit','delete'],
'messages' => ['show','update']
],
'user' => [ 'index' => ['index','sign-out'],
'messages' => ['show','index']
]
}
How can i check what access['admin']['users']['edit'] exists?

access['admin']['users'].include? 'edit'
However, this may be a problem: you're using ... => ['users'=>['edit','delete'],...]
This will create an array with a hash inside. Example:
{'a'=>'b'} #=> {"a"=>"b"}
['a'=>'b'] #=> [{"a"=>"b"}]
So consider using this:
access = {
'admin' => { 'users' => ['edit','delete'],
'messages' => ['show','update']
},
'user' => { 'index' => ['index','sign-out'],
'messages' => ['show','index']
}
}

Related

yii2 pagecahe array dependecny

I am implementing page cache for one of my page. For depenedency, I have to check an array, which can be either exist or not. Possible array keys cane ,
usersearch['id'], usersearch['name'], usersearch['phone]. I have to add dependency for any change in these values as well.
Also, I have to clear cache for any update or add in user table.
Is there any possible solution for this.?
Thanks in advance
You can use variations
public function behaviors(){
$usersearch = Yii::$app->requst->get('usersearch');
return [
[
'class' => 'yii\filters\PageCache',
'only' => ['index'],
'duration' => 60,
'variations' => [
'YOUR_DYNAMIC_VALUE1','YOUR_DYNAMIC_VALUE2'
],
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT COUNT(*) FROM post',
],
],
];
}
Ref link
IN YOUR CASE ,you can use
'variations' => \Yii::$app->requst->get('usersearch')??[],
or
'variations' => [
\/Yii::$app->requst->get('usersearch')['id'] ?? '',
\Yii::$app->requst->get('usersearch')['name'] ?? '',
\Yii::$app->requst->get('usersearch')['phone'] ?? '',
]
You could use a yii\caching\FileCache component with the following configuration.
Firstly, you set the cache in the init function of your controller:
Yii::$app->setComponents([
'yourCacheName' => [
'class' => \yii\caching\FileCache::class,
'defaultDuration' => 1800, //cache duration in seconds
'keyPrefix' => Yii::$app->getSession()->getId(). '_'
]
]);
Here, the parameter keyPrefix is set so that it is linked to the session ID. Thus, the visitors do not see each other's cached page. If the content is static and equal, regardless of the user or the session, this parameter can be removed.
In the view that must be cached you can call the beginCache function and the dependency as follows:
$this->beginCache('cache-id', [
'cache' => Yii::$app->yourCacheName, // the name of the component as set before
'variations' => [
$usersearch['id'] ?? '',
$usersearch['name'] ?? '',
$usersearch['phone'] ?? '',
],
'dependency' => [
'class' => \yii\caching\DbDependency::class,
'sql' => 'SELECT count(*) FROM your_user_table'
]
]);
// your view
$this->endCache();

Concatenating two arrays and sum with keys via Laravel Collection

I'm having a set of array in something like this format:
[
{"GA_1":"1","GA_2":null,"GA_3":null,"GA_4":null},
{"SA_1":null,"SA_2":"2","SA_3":null,"SA_4":null},
{"RA_1":"1","RA_2":null,"RA_3":null,"RA_4":null}
]
I'm storing this in my mysql text column in json_decoded format. I want to call all the eloquent models and merge these arrays with sum of the each keys on object. For example
1st row contains:
[
{"GA_1":"1","GA_2":null,"GA_3":null,"GA_4":null},
{"SA_1":null,"SA_2":"2","SA_3":null,"SA_4":null},
{"RA_1":"1","RA_2":null,"RA_3":null,"RA_4":null}
]
2nd row contains:
[
{"GA_1":null,"GA_2":"1","GA_3":"2","GA_4":null},
{"SA_1":"1","SA_2":null,"SA_3":"3","SA_4":null},
{"RA_1":null,"RA_2":"2","RA_3":null,"RA_4":"5"}
]
3rd row contains:
[
{"GA_1":"1","GA_2":null,"GA_3":null,"GA_4":null},
{"SA_1":null,"SA_2":"2","SA_3":null,"SA_4":null},
{"RA_1":"1","RA_2":null,"RA_3":null,"RA_4":null}
]
so my final output should be:
[
{"GA_1":"2","GA_2":"1","GA_3":"2","GA_4":null},
{"SA_1":"1","SA_2":"4","SA_3":null,"SA_4":null},
{"RA_1":"1","RA_2":"2","RA_3":null,"RA_4":"5"}
]
I'm stuck in how can I achieve this:
$games = Game::get();
$grid = [];
foreach ($games as $game) {
$grid[] = collect($game->grid_values);
}
dd(collect('$grid')->flatten());
I'm getting this output:
Any suggestions are welcome. Thanks.
Well I tried something like this:
$games = Game::get();
$d = collect($games)->map(function($item) {
return json_decode($item->grid_values);
})->flatten();
$x = collect([
[
'GA_1' => $d->sum('GA_1'),
'GA_2' => $d->sum('GA_2'),
'GA_3' => $d->sum('GA_3'),
'GA_4' => $d->sum('GA_4'),
'GA_5' => $d->sum('GA_5'),
'GA_6' => $d->sum('GA_6'),
'GA_7' => $d->sum('GA_7'),
'GA_8' => $d->sum('GA_8'),
'GA_9' => $d->sum('GA_9'),
'GA_0' => $d->sum('GA_0'),
],
[
'SA_1' => $d->sum('SA_1'),
'SA_2' => $d->sum('SA_2'),
'SA_3' => $d->sum('SA_3'),
'SA_4' => $d->sum('SA_4'),
'SA_5' => $d->sum('SA_5'),
'SA_6' => $d->sum('SA_6'),
'SA_7' => $d->sum('SA_7'),
'SA_8' => $d->sum('SA_8'),
'SA_9' => $d->sum('SA_9'),
'SA_0' => $d->sum('SA_0'),
],
[
'RA_1' => $d->sum('RA_1'),
'RA_2' => $d->sum('RA_2'),
'RA_3' => $d->sum('RA_3'),
'RA_4' => $d->sum('RA_4'),
'RA_5' => $d->sum('RA_5'),
'RA_6' => $d->sum('RA_6'),
'RA_7' => $d->sum('RA_7'),
'RA_8' => $d->sum('RA_8'),
'RA_9' => $d->sum('RA_9'),
'RA_0' => $d->sum('RA_0'),
],
]);
return response()->json(['data' => $x], 200);
And I got expected result, any improvisation please suggest.

YII2: custom sorting in search model

Please, help me with such a problem:
1) I have default search model of Users.
2) I need a list of users. And first in this list always must be user with login 'admin', and second - with login 'finance', and then all others sorted by id.
My method in UserController
public function actionUsersList() {
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('users-list', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
As I understood I have to change params of search in this line, to add sort conditions
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
But how exactly can I do this?
You can do that by adding following code to your action:
$dataProvider->sort->attributes['id'] = [
'asc' => [
new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
'id' => SORT_ASC,
],
'desc' => [
new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
'id' => SORT_DESC,
],
'label' => $searchModel->getAttributeLabel('id'),
];
$dataProvider->sort->defaultOrder = ['id' => SORT_ASC];
The field function returns the position of first parameter among other parameters or 0 if the value is not present among them. So for 'admin' it will return 2, for 'finance' 1 and for others 0. If you order DESC by that you will get the required order.
Other option is to add this definitions for sort into the search method of UserSearch model as suggested in mahsaa's answer. It depenends if you want to use this sorting in different actions.
In UserSearch class, add sort to ActiveDataProvider:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'login' => SORT_ASC,
'id' => SORT_DESC,
],
]]);
It first sorts by login and then id.

how to stop execution of ctp file in cakephp 2.x after validating the url

In my CakePHP application, I have applied Url validations so that admin can access only those actions which are defined for admin and same as with users.
In my application, "surveylist" is the action of admin and when any user directly access that action(surveylist), URL validations work(Unauthorized access msg is displayed).
But below that message ctp file of surveylist executes forcefully and show errors because I have validated URL through the try-catch block and it cannot get the set variables of action.
I want that ctp file should not execute if unauthorize error comes.
My code for surveylist is:-
public function surveylist($pg=null){
try{
if($this->checkPageAccess($this->params['controller'] . '/' . $this->params['action'])){
$this->Paginator->settings = array(
'Survey' => array(
'limit' => 5,
'order' => 'created desc',
'conditions'=>array('is_deleted'=> 0),
'page' => $pg
)
);
$numbers = $this->Paginator->paginate('Survey');
$this->set(compact('numbers'));
}else{
$this->Flash->set(__('Unauthorised access'));
}
}catch(Exception $e){
$this->Flash->set(__($e->getMessage()));
}
}
I don't want the ctp file of surveylist to execute if control comes to else.
Plz, help me out......
Thanx in advance...
I suppose you are using prefix to separate admin and users, if not please do that it is great way to handle and restrict methods.
After doing that you have to make condition to check which prefix(admin, user) is currently active and according that load Auth component and allow action in allow() method of Auth.
Example:
$this->loadComponent('Auth',[
/*'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],*/
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => false
],
'authError' => 'You are not authorized to access that location.',
]);
if ($this->request->params['prefix']=='admin') {
// Put actions you want to access to admin in allow method's array
$this->Auth->allow(array('add', 'edit', etc...));
} else if ($this->request->params['prefix']=='user') {
// Put actions you want to access to user in allow method's array
$this->Auth->allow(array('login', 'view', etc...));
}
This way you can restrict actions for particular role.
Hope this helps!

Installing user-management for Yii2.0

I've been trying to install user-management for Yii2.0, but getting ReflectionException while loading the page. I have attached the error page and directory structure below.
and the file path is as shown below.
I've searched a lot to find out the reason for this, but nothing worked out. can someone tell me what am I missing here to get it work. looks like the user-management installation documentation has some flaws. It is not clear enough to understand. Hope to get the steps to install. Thanks
Here is my console/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gAry7SfUr0oOjNQDqItsobmGBcJajQoW',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
//'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'class' => 'app\webvimark\modules\user-management\components\UserConfig',
// Comment this if you don't want to record user logins
'on afterLogin' => function($event) {
\webvimark\modules\user-management\models\UserVisitLog::newVisitor($event->identity->id);
}
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules'=>[
'user-management' => [
'class' => 'webvimark\modules\user-management\UserManagementModule',
// 'enableRegistration' => true,
// Here you can set your handler to change layout for any controller or action
// Tip: you can use this event in any module
'on beforeAction'=>function(yii\base\ActionEvent $event) {
if ( $event->action->uniqueId == 'user-management/auth/login' )
{
$event->action->controller->layout = 'loginLayout.php';
};
},
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
It seems to have a slight difference with the expected configuration for this extension.
Use this
'class' => 'webvimark\modules\UserManagement\components\UserConfig',
ie UserManagement instead of user-management is a configuration path and not a route

Resources