heres my api.php file code in try body else case is taking too much time
<?php
require_once(dirname(__FILE__) . "/constants.php");
includeMonstaConfig();
session_start();
require_once(dirname(__FILE__) . '/lib/helpers.php');
require_once(dirname(__FILE__) . '/lib/response_helpers.php');
require_once(dirname(__FILE__) . '/request_processor/RequestMarshaller.php');
if (file_exists(dirname(__FILE__) . '/../../mftp_extensions.php')) {
include_once(dirname(__FILE__) . '/../../mftp_extensions.php');
}
dieIfNotPOST();
require_once(dirname(__FILE__) . '/lib/access_check.php');
$marshaller = new RequestMarshaller();
try {
$request = json_decode($_POST['request'], true);
if ($request['actionName'] == 'fetchFile' || $request['actionName'] == 'downloadMultipleFiles') {
switch ($request['actionName']) {
case 'fetchFile':
$outputPath = $marshaller->prepareFileForFetch($request);
$outputFileName = monstaBasename($request['context']['remotePath']);
break;
case 'downloadMultipleFiles':
$outputResponse = $marshaller->marshallRequest($request, false, true);
$outputPath = $outputResponse["data"];
$outputFileName = "mftp_zip_" . date("Y_m_d_H_i_s") . ".zip";
}
$fileKey = generateRandomString(16);
$_SESSION[MFTP_SESSION_KEY_PREFIX . $fileKey] = array(
"path" => $outputPath,
"fileName" => $outputFileName
);
$response = array(
"success" => true,
"fileKey" => $fileKey
);
print json_encode($response);
} else {
$skipConfigurationActions = array('checkSavedAuthExists', 'writeSavedAuth', 'readSavedAuth',
'readLicense', 'getSystemVars', 'resetPassword', 'forgotPassword', 'validateSavedAuthPassword',
'downloadLatestVersionArchive', 'installLatestVersion');
$skipConfiguration = in_array($request['actionName'], $skipConfigurationActions);
$serializedResponse = $marshaller->marshallRequest($request, $skipConfiguration);
print $serializedResponse;
}
} catch (Exception $e) {
$marshaller->disconnect();
handleExceptionInRequest($e);
}
$marshaller->disconnect();
here is the RequestMarshaller.php code showing only the request code
<?php
require_once(dirname(__FILE__) . '/RequestDispatcher.php');
require_once(dirname(__FILE__) . "/../lib/helpers.php");
require_once(dirname(__FILE__) . "/../system/ApplicationSettings.php");
class RequestMarshaller {
/**
* #var RequestDispatcher
*/
private $requestDispatcher;
private function initRequestDispatcher($request, $skipConfiguration = false) {
if(!$skipConfiguration)
$request['configuration'] = $this->applyConnectionRestrictions($request['connectionType'],
$request['configuration']);
if (is_null($this->requestDispatcher))
$this->requestDispatcher = new RequestDispatcher($request['connectionType'], $request['configuration'],
null, null, $skipConfiguration);
}
public function marshallRequest($request, $skipConfiguration = false, $skipEncode = false) {
$this->initRequestDispatcher($request, $skipConfiguration);
$response = array();
if ($request['actionName'] == 'putFileContents')
$response = $this->putFileContents($request);
else if ($request['actionName'] == 'getFileContents')
$response = $this->getFileContents($request);
else {
$context = array_key_exists('context', $request) ? $request['context'] : null;
$responseData = $this->requestDispatcher->dispatchRequest($request['actionName'], $context);
$response['success'] = true;
if(is_object($responseData)) {
$response['data'] = method_exists($responseData, 'legacyJsonSerialize') ?
$responseData->legacyJsonSerialize() : $responseData;
} else
$response['data'] = $responseData;
}
if ($skipEncode)
return $response;
return json_encode($response);
}
}
}
and here is my RequestDispatcher.php code
<?php
class RequestDispatcher {
/**
* #var ConnectionBase
*/
private $connection;
/**
* #var string
*/
private $connectionType;
/**
* #var array
*/
private $rawConfiguration;
public $username;
public function getusername(){
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
return $this->username;
}
public function __construct($connectionType, $rawConfiguration, $configurationFactory = null,
$connectionFactory = null, $skipConfiguration = false) {
$this->connectionType = $connectionType;
/* allow factory objects to be passed in for testing with mocks */
if ($skipConfiguration) {
$this->connection = null;
} else {
$this->rawConfiguration = $rawConfiguration;
$configurationFactory = is_null($configurationFactory) ? new ConfigurationFactory() : $configurationFactory;
$connectionFactory = is_null($connectionFactory) ? new ConnectionFactory() : $connectionFactory;
$configuration = $configurationFactory->getConfiguration($connectionType, $rawConfiguration);
$this->connection = $connectionFactory->getConnection($connectionType, $configuration);
}
}
public function dispatchRequest($actionName, $context = null) {
if (in_array($actionName, array(
'listDirectory',
'downloadFile',
'uploadFile',
'deleteFile',
'makeDirectory',
'deleteDirectory',
'rename',
'changePermissions',
'copy',
'testConnectAndAuthenticate',
'checkSavedAuthExists',
'writeSavedAuth',
'readSavedAuth',
'readLicense',
'getSystemVars',
'fetchRemoteFile',
'uploadFileToNewDirectory',
'downloadMultipleFiles',
'createZip',
'setApplicationSettings',
'deleteMultiple',
'extractArchive',
'updateLicense',
'reserveUploadContext',
'transferUploadToRemote',
'getRemoteFileSize',
'getDefaultPath',
'downloadForExtract',
'cleanUpExtract',
'resetPassword',
'forgotPassword',
'validateSavedAuthPassword',
'downloadLatestVersionArchive',
'installLatestVersion'
))) {
if (!is_null($context))
return $this->$actionName($context);
else
return $this->$actionName();
}
throw new InvalidArgumentException("Unknown action $actionName");
}
public function getConnection() {
return $this->connection;
}
private function connectAndAuthenticate($isTest = false) {
$sessionNeedsStarting = false;
if (function_exists("session_status")) {
if (session_status() == PHP_SESSION_NONE) {
$sessionNeedsStarting = true;
}
} else {
$sessionNeedsStarting = session_id() == "";
}
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
if ($sessionNeedsStarting && !defined("MONSTA_UNIT_TEST_MODE")) { // TODO: pass in this as parameter to avoid global state
session_start();
$_SESSION["RemoteUsername"]=$configuration->getRemoteUsername();
}
$maxFailures = defined("MFTP_MAX_LOGIN_FAILURES") ? MFTP_MAX_LOGIN_FAILURES : 0;
$loginFailureResetTimeSeconds = defined("MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES")
? MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES * 60 : 0;
if (!isset($_SESSION["MFTP_LOGIN_FAILURES"]))
$_SESSION["MFTP_LOGIN_FAILURES"] = array();
$banManager = new UserBanManager($maxFailures, $loginFailureResetTimeSeconds,
$_SESSION["MFTP_LOGIN_FAILURES"]);
if ($banManager->hostAndUserBanned($configuration->getHost(), $configuration->getRemoteUsername())) {
mftpActionLog("Log in", $this->connection, "", "", "Login and user has exceed maximum failures.");
throw new FileSourceAuthenticationException("Login and user has exceed maximum failures.",
LocalizableExceptionDefinition::$LOGIN_FAILURE_EXCEEDED_ERROR, array(
"banTimeMinutes" => MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES
));
}
try {
$this->connection->connect();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
throw $e;
}
try {
$this->connection->authenticate();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
$banManager->recordHostAndUserLoginFailure($configuration->getHost(),
$configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
throw $e;
}
$banManager->resetHostUserLoginFailure($configuration->getHost(), $configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
if ($isTest) {
// only log success if it is the first connect from the user
mftpActionLog("Log in", $this->connection, "", "", "");
}
if ($configuration->getInitialDirectory() === "" || is_null($configuration->getInitialDirectory())) {
return $this->connection->getCurrentDirectory();
}
return null;
}
public function disconnect() {
if ($this->connection != null && $this->connection->isConnected())
$this->connection->disconnect();
}
public function listDirectory($context) {
$this->connectAndAuthenticate();
$directoryList = $this->connection->listDirectory($context['path'], $context['showHidden']);
$this->disconnect();
return $directoryList;
}
public function downloadFile($context, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->downloadFile($transferOp);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also downloaded
mftpActionLog("Download file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function downloadMultipleFiles($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$zipPath = $zipBuilder->buildZip($foundFiles);
$this->disconnect();
return $zipPath;
}
public function createZip($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$destPath = PathOperations::join($context['baseDirectory'], $context['dest']);
$zipPath = $zipBuilder->buildLocalZip($foundFiles, $destPath);
$this->connection->uploadFile(new FTPTransferOperation($zipPath, $destPath, FTP_BINARY));
$this->disconnect();
return $zipPath;
}
public function uploadFile($context, $preserveRemotePermissions = false, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFile($transferOp, $preserveRemotePermissions);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also uploaded
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function uploadFileToNewDirectory($context) {
// This will first create the target directory if it doesn't exist and then upload to that directory
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFileToNewDirectory($transferOp);
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
$this->disconnect();
}
public function deleteFile($context) {
$this->connectAndAuthenticate();
$this->connection->deleteFile($context['remotePath']);
mftpActionLog("Delete file", $this->connection, dirname($context['remotePath']), monstaBasename($context['remotePath']), "");
$this->disconnect();
}
public function makeDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->makeDirectory($context['remotePath']);
$this->disconnect();
}
public function deleteDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->deleteDirectory($context['remotePath']);
$this->disconnect();
}
public function rename($context) {
$this->connectAndAuthenticate();
if(array_key_exists('action', $context) && $context['action'] == 'move') {
$action = 'Move';
} else {
$action = 'Rename';
}
$itemType = $this->connection->isDirectory($context['source']) ? 'folder' : 'file';
$this->connection->rename($context['source'], $context['destination']);
if ($action == 'Move') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . $context['destination'],
"");
}
if ($action == 'Rename') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . monstaBasename($context['destination']),
"");
}
$this->disconnect();
}
public function changePermissions($context) {
$this->connectAndAuthenticate();
$itemType = $this->connection->isDirectory($context['remotePath']) ? 'folder' : 'file';
$this->connection->changePermissions($context['mode'], $context['remotePath']);
mftpActionLog("CHMOD " . $itemType, $this->connection, dirname($context['remotePath']),
monstaBasename($context['remotePath']) . " to " . decoct($context['mode']), "");
$this->disconnect();
}
public function copy($context) {
$this->connectAndAuthenticate();
$this->connection->copy($context['source'], $context['destination']);
$this->disconnect();
}
public function testConnectAndAuthenticate($context, $isInitalLogin = true) {
$initialDirectory = $this->connectAndAuthenticate($isInitalLogin);
$serverCapabilities = array("initialDirectory" => $initialDirectory);
if (isset($context['getServerCapabilities']) && $context['getServerCapabilities']) {
$serverCapabilities["changePermissions"] = $this->connection->supportsPermissionChange();
}
clearOldTransfers();
return array("serverCapabilities" => $serverCapabilities);
}
public function checkSavedAuthExists() {
if ($this->readLicense() == null)
return false;
return AuthenticationStorage::configurationExists(AUTHENTICATION_FILE_PATH);
}
public function writeSavedAuth($context) {
if ($this->readLicense() == null)
return;
AuthenticationStorage::saveConfiguration(AUTHENTICATION_FILE_PATH, $context['password'],
$context['authData']);
}
public function readSavedAuth($context) {
if ($this->readLicense() == null)
return array();
return AuthenticationStorage::loadConfiguration(AUTHENTICATION_FILE_PATH, $context['password']);
}
public function readLicense() {
$keyPairSuite = new KeyPairSuite(PUBKEY_PATH);
$licenseReader = new LicenseReader($keyPairSuite);
$license = $licenseReader->readLicense(MONSTA_LICENSE_PATH);
if (is_null($license))
return $license;
$publicLicenseKeys = array("expiryDate", "version", "isTrial", "licenseVersion", "productEdition");
$publicLicense = array();
foreach ($publicLicenseKeys as $publicLicenseKey) {
if (isset($license[$publicLicenseKey]))
$publicLicense[$publicLicenseKey] = $license[$publicLicenseKey];
}
return $publicLicense;
}
private function recordAffiliateSource($licenseEmail) {
$affiliateChecker = new AffiliateChecker();
$installUrl = getMonstaInstallUrl();
$affiliateId = defined("MFTP_AFFILIATE_ID") ? MFTP_AFFILIATE_ID : "";
return $affiliateChecker->recordAffiliateSource($affiliateId, $licenseEmail, $installUrl);
}
public function getSystemVars() {
$systemVars = SystemVars::getSystemVarsArray();
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$systemVars['applicationSettings'] = $applicationSettings->getSettingsArray();
return $systemVars;
}
public function setApplicationSettings($context) {
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$applicationSettings->setFromArray($context['applicationSettings']);
$applicationSettings->save();
}
public function validateSavedAuthPassword($context) {
return AuthenticationStorage::validateAuthenticationPassword(AUTHENTICATION_FILE_PATH, $context["password"]);
}
}
i am not that much experienced in this field i am a beginner and got this task to find out the cause of the delay and resolve it . kindly help me in this regard i have tried many things as i thought that json_encoding(response) might be the cause but just 10 items are returning in response
I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}
From the model TagModel i can filter the value which i want it, but value is stored in the form of object variable. To play with those data in controller i am not able to pluck the particular id.
This is my model
public static function getLatestTag($name){
return $tagIds =DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->get();
}
This is my controller code:
foreach ($newTags as $newTag) {
$productTagIds[] = TagModel::getLatestTag($newTag);
dd($id);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($productTagIds as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
the value which i want is stored in the variable $productTagIds which is object variable. How can I pluck just id from this?
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
$productTagIds[]=$objectTagProduct->id;
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
The code might flash a certain error that have to troubleshoot by yourself. I have kept
$productTagIds[]=$objectTagProduct->id;
after $objectTagProduct->save(); please try it
public static function getLatestTag($name){
return $tagIds = DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->pluck(id);
}
public static function getLatestTag($name){
return App\TagModel::where('is_deleted',0)->where('name',$name)->first()->id;
}
$ids = [];
foreach ($newTags as $newTag) {
$productTagId = TagModel::getLatestTag($newTag);
array_push($ids,$productTagId);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($ids as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
try to use eloquent like this
to get the particular value from the object class variable
$productTagIds[]=$objectTagProduct->id;`
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTagIds[]=$objectTagProduct->id;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
I came to knew that to get the data from object class variable $productTagIds[]=$objectTagProduct->id;
But i am confused with its flow and where to execute this code.
I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.
I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';