google socialite laravel 8 return after authentication a blank screen - laravel-socialite

when i am tring to authenticate with google account it returns an empty string i don't know why so can u help me find this error i made the all steps requiring to do the authentication it returns callback with an empty string and my client_id and client secret are correct
here is my code google controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class GoogleController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
/**
* Create a new controller instance.
*
* #return void
*/
public function handleGoogleCallback()
{
try {
$user = Socialite::driver('google')->user();
$finduser = User::where('social_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect()->intended('dashboard');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'social_id'=> $user->id,
'social_type'=> 'google',
'password' => encrypt('123456dummy')
]);
Auth::login($newUser);
return redirect()->intended('dashboard');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
and my routes
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified'
])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::get('auth/google', [App\Http\Controllers\GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [App\Http\Controllers\GoogleController::class, 'handleGoogleCallback']);
my config/services.php
'google' => [
'client_id' => '982061662199-bns94j425f1cgq7p8b0eo4lctjn83e4e.apps.googleusercontent.com',
'client_secret' => 'GOCSPX-9AFn2bhebi2yPUpCU8_LIzfb',
'redirect' => 'http://localhost:8000/auth/google/callback',
],

Related

error in codeigniter 4 You must set the database table to be used with your query

i am working codeigniter 4. i am trying to fetch data from database by creating method in Model but am getting error
You must set the database table to be used with your query
even I have mentioned the table name in query builder. i dun know why this is happening ? following is my code
public function Login($values)
{
$db = \Config\Database::connect();
$result= $db->table('tbl_adminuser')
->where(['username',$values['username']])
->where(['password',$values['password']])
->get()
->getResult();
print_r($result);
}
There are two types of getting data from the database.
Using the Model file
Load db in the controller file
Check both the below types to get data from the database.
1. Using the Model file
First, create a User model and mention the name of the database table.
Here is the sample of model file:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserMasterModel extends Model
{
protected $table = 'user_master';
}
Then create a controller file and load the model using use App\Models\UserMasterModel;.
You should following the below sample of the controller file there is mention load the model and get the data using a model file.
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserMasterModel;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function Login($values){
$UserMasterModel = new UserMasterModel();
$result = $UserMasterModel->where('username',$values['username'])
->where('password',$values['password'])
->findAll();
print_r($result);
}
2. Load db in controller file
When using \Config\Database::connect() the controller file looks like below:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->user_master = $this->db->table('user_master');
}
public function Login($values){
$this->user_master->select('*');
$this->user_master->where('username',$values['username']);
$this->user_master->where('password',$values['password']);
$result = $this->user_master->get()->getResult();
print_r($result);
}
create model for users
<?php namespace Myth\Auth\Models;
use CodeIgniter\Model;
use Myth\Auth\Authorization\GroupModel;
use Myth\Auth\Entities\User;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = User::class;
protected $useSoftDeletes = false;
protected $allowedFields = [
'email', 'username', 'password_hash', 'reset_hash', 'reset_at', 'reset_expires', 'activate_hash',
'status', 'status_message', 'active', 'force_pass_reset', 'permissions',
'first_name',
'last_name',
'image',
'address',
'phone',
'email',
'gender',
'country',
'city',
'created_at',
'updated_at',
'deleted_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'email' => 'if_exist|required|valid_email|is_unique[users.email,id,{id}]',
'phone' => 'if_exist|required|is_unique[users.phone,id,{id}]',
'username' => 'if_exist|required|alpha_numeric_punct|min_length[3]|max_length[30]|is_unique[users.username,id,{id}]',
'password_hash' => 'if_exist|required',
];
protected $validationMessages = [];
protected $skipValidation = false;
protected $afterInsert = ['addToGroup'];
/**
* The id of a group to assign.
* Set internally by withGroup.
*
* #var int|null
*/
protected $assignGroup;
/**
* Logs a password reset attempt for posterity sake.
*
* #param string $email
* #param string|null $token
* #param string|null $ipAddress
* #param string|null $userAgent
*/
public function logResetAttempt(string $email, string $token = null, string $ipAddress = null, string $userAgent = null)
{
$this->db->table('auth_reset_attempts')->insert([
'email' => $email,
'ip_address' => $ipAddress,
'user_agent' => $userAgent,
'token' => $token,
'created_at' => date('Y-m-d H:i:s')
]);
}
/**
* Logs an activation attempt for posterity sake.
*
* #param string|null $token
* #param string|null $ipAddress
* #param string|null $userAgent
*/
public function logActivationAttempt(string $token = null, string $ipAddress = null, string $userAgent = null)
{
$this->db->table('auth_activation_attempts')->insert([
'ip_address' => $ipAddress,
'user_agent' => $userAgent,
'token' => $token,
'created_at' => date('Y-m-d H:i:s')
]);
}
/**
* Sets the group to assign any users created.
*
* #param string $groupName
*
* #return $this
*/
public function withGroup(string $groupName)
{
$group = $this->db->table('auth_groups')->where('name', $groupName)->get()->getFirstRow();
$this->assignGroup = $group->id;
return $this;
}
/**
* Clears the group to assign to newly created users.
*
* #return $this
*/
public function clearGroup()
{
$this->assignGroup = null;
return $this;
}
/**
* If a default role is assigned in Config\Auth, will
* add this user to that group. Will do nothing
* if the group cannot be found.
*
* #param mixed $data
*
* #return mixed
*/
protected function addToGroup($data)
{
if (is_numeric($this->assignGroup)) {
$groupModel = model(GroupModel::class);
$groupModel->addUserToGroup($data['id'], $this->assignGroup);
}
return $data;
}
}
too use model
$model = new usermodel();
$model->asObject()->where('active', '1')->findAll();

In EasyAdmin 3 configureActions method how do I get the current entity?

I wish to add an action to another to the index action with a predefined filter.
To build the filter I need the get current entity in the configureActions method.
public function configureActions(Actions $actions): Actions
{
parent::configureActions($actions);
$adminUrlGenerator = $this->get(AdminUrlGenerator::class);
$url = $adminUrlGenerator
->setController(SiteCrudController::class)
->setAction(Action::INDEX)
->set('filters', [
'agent' => [
'comparison' => '=',
'value' => 2194, // How to get current entity here??
]
])
->generateUrl()
;
$viewRelatesSites = Action::new('viewRelatedSites', 'Sites', 'fa fa-file-invoice')
->linkToUrl($url)
;
$actions->add(Action::DETAIL, $viewRelatesSites);
$actions->add(Action::EDIT, $viewRelatesSites);
return $actions;
}
}
How can I get the entity here?
To get the current entity the AdminContext is needed.
The best place to get this with the entity set is in a BeforeCrudActionEvent.
final class AgentCrudActionEventListen implements EventSubscriberInterface
{
private AdminUrlGenerator $adminUrlGenerator;
private AdminContextProvider $adminContextProvider;
public function __construct(AdminUrlGenerator $adminUrlGenerator, AdminContextProvider $adminContextProvider)
{
$this->adminUrlGenerator = $adminUrlGenerator;
$this->adminContextProvider = $adminContextProvider;
}
public static function getSubscribedEvents(): array
{
return [
BeforeCrudActionEvent::class => 'onBeforeCrudActionEvent',
];
}
public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event): void
{
$crud = $event->getAdminContext()->getCrud();
if ($crud->getControllerFqcn() !== AgentCrudController::class) {
return;
}
$entity = $this->adminContextProvider->getContext()->getEntity();
if (!$entity) {
return;
}
$url = $this->adminUrlGenerator
->setController(SiteCrudController::class)
->setAction(Action::INDEX)
->set('filters', [
'agent' => [
'comparison' => '=',
'value' => $entity->getPrimaryKeyValue(),
]
])
->generateUrl()
;
$viewRelatedSites = Action::new('viewRelatedSites', 'Sites', 'fa fa-file-invoice')
->linkToUrl($url)
;
$actions = $crud->getActionsConfig();
$actions->appendAction(Action::DETAIL, $viewRelatedSites->getAsDto());
$actions->appendAction(Action::EDIT, $viewRelatedSites->getAsDto());
}
}
After a day looking for the current entity into my AbstractCrudController, I found this :
$currentEntity = $this->getContext()->getEntity()->getInstance();
Since EasyAdmin 3 events are discouraged per the docs:
Starting from EasyAdmin 3.0 everything is defined with PHP. That's why it's easier to customize backend behavior overloading PHP classes and methods and calling to your own services. However, the events still remain in case you want to use them.
public function configureActions(Actions $actions): Actions
{
// Create your action
$viewRelatedSites = Action::new('viewRelatedSites', 'Sites', 'fa fa-file-invoice');
//set the link using a string or a callable (function like its being used here)
$viewRelatedSites->linkToUrl(function($entity) {
$adminUrlGenerator = $this->get(AdminUrlGenerator::class);
$url = $adminUrlGenerator
->setController(SiteCrudController::class)
->setAction(Action::INDEX)
->set('filters', [
'agent' => [
'comparison' => '=',
'value' => $entity->getId()
]
])
->generateUrl();
return $url;
});
$actions->add(Crud::PAGE_INDEX, $viewRelatedSites);
return $actions;
}

Electron - How to create deep-linking on linux

I have an ElectronJS project and I use the protocols (deep-link) in this one. It's work on MacOS and Windows but on Linux I can't understand how to create this protocol.
I have looked in the ElectronJS documentation as well as on the web for issues etc. but I can't figure out how to initialize protocol on Linux. All I want is to achieve, as I have succeeded on MacOS and Windows, a protocol to interact with the app in deep-link.
Code that works on MacOS and Windows :
// main.ts
// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
ProtocolUtils.setDefaultProtocolClient();
// eslint-disable-next-line default-case
switch (process.platform) {
case 'darwin':
ProtocolUtils.setProtocolHandlerOSX();
break;
case 'win32':
ProtocolUtils.setProtocolHandlerWin32();
break;
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// protocol.ts
export abstract class ProtocolUtils {
/**
* #description Create default protocole for call this app.
* Ex : in your browser => myapp://test
*/
public static setDefaultProtocolClient(): void {
if (!app.isDefaultProtocolClient('myapp')) {
// Define custom protocol handler.
// Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp');
}
}
/**
* #description Create logic (WIN32) for open url from protocol
*/
public static setProtocolHandlerWin32(): void {
// Force Single Instance Application on win32
const gotTheLock = app.requestSingleInstanceLock();
app.on('second-instance', (e: Electron.Event, argv: string[]) => {
// Someone tried to run a second instance, we should focus our window.
if (MainWindow.mainWindow) {
if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
MainWindow.mainWindow.focus();
} else {
MainWindow.openMainWindow(); // Open main windows
}
app.whenReady().then(() => {
MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32(argv)); // Load URL in WebApp
});
});
if (gotTheLock) {
app.whenReady().then(() => {
MainWindow.openMainWindow(); // Open main windows
MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32()); // Load URL in WebApp
});
} else {
app.quit();
}
}
/**
* #description Create logic (OSX) for open url from protocol
*/
public static setProtocolHandlerOSX(): void {
app.on('open-url', (event: Electron.Event, url: string) => {
event.preventDefault();
app.whenReady().then(() => {
MainWindow.openMainWindow(); // Open main windows
MainWindow.mainWindow.loadURL(this._getUrlToLoad(url)); // Load URL in WebApp
});
});
}
/**
* #description Format url to load in mainWindow
*/
private static _getUrlToLoad(url: string): string {
// Ex: url = myapp://deep-link/test?params1=paramValue
// Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
const urlSplitted = url.split('//');
// Generate URL to load in WebApp.
// Ex: file://path/index.html#deep-link/test?params1=paramValue
const urlToLoad = format({
pathname: Env.BUILDED_WEBAPP_INDEX_PATH,
protocol: 'file:',
slashes: true,
hash: `#${urlSplitted[1]}`,
});
return urlToLoad;
}
/**
* #description Resolve deep link url for windows from process argv
*/
private static _getDeepLinkUrlForWin32(argv?: string[]): string {
let url: string;
const newArgv: string[] = !isNil(argv) ? argv : process.argv;
// Protocol handler for win32
// argv: An array of the second instance’s (command line / deep linked) arguments
if (process.platform === 'win32') {
// Get url form precess.argv
newArgv.forEach((arg) => {
if (/myapp:\/\//.test(arg)) {
url = arg;
}
});
if (!isNil(url)) {
return this._getUrlToLoad(url); // Load URL in WebApp
} else if (!isNil(argv) && isNil(url)) {
throw new Error('URL is undefined');
}
}
}
}
I have no worries for macOS and windows, but on linux the protocol does not exist even with the line :
ProtocolUtils.setDefaultProtocolClient(); who is responsible for creating the myapp: // protocol...
When I run this command : xdg-open myapp://deep-link/test?toto=titi An error tells me that this protocol does not exist
If anyone has an example for me to configure on Linux or can just help me ?
Thanks
Ok i have found the solution !
First, we removed electron-forge and replaced it with electron-builder (cf doc).
Then after reading a lot of documentation for deep links on Linux, Examples of documentation :
Desktop file
Specification of desktop entry
Electron builder desktop file
And my solution is :
# electron-builder.yml
appId: com.myapp.myapp
productName: myapp
directories:
output: out
linux:
icon: src/assets/icons/app/icon#256x256.png
category: Utility
mimeTypes: [x-scheme-handler/myapp] # Define MimeType
desktop: # Define desktop elem
exec: myapp %u # Define Exec
target:
- target: deb
arch:
- x64
So i defined the MimeType with the name of my protocol here myapp which could give:
myapp://toto?foo=bar
And in my desktop file define Exec with myapp %u because %u => A single URL. Local files may either be passed as file: URLs or as file path. (cf doc)
And for finish in my main.ts and protocol.utils.ts:
// main.ts
// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
ProtocolUtils.setDefaultProtocolClient();
switch (process.platform) {
case 'darwin':
ProtocolUtils.setProtocolHandlerOSX();
break;
case 'linux':
case 'win32':
ProtocolUtils.setProtocolHandlerWindowsLinux();
break;
default:
throw new Error('Process platform is undefined');
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// protocol.utils.ts
export abstract class ProtocolUtils {
public static setDefaultProtocolClient(): void {
if (!app.isDefaultProtocolClient('myapp')) {
// Define custom protocol handler.
// Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp');
}
}
/**
* #description Create logic (WIN32 and Linux) for open url from protocol
*/
public static setProtocolHandlerWindowsLinux(): void {
// Force Single Instance Application
const gotTheLock = app.requestSingleInstanceLock();
app.on('second-instance', (e: Electron.Event, argv: string[]) => {
// Someone tried to run a second instance, we should focus our window.
if (MainWindow.mainWindow) {
if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
MainWindow.mainWindow.focus();
} else {
// Open main windows
MainWindow.openMainWindow();
}
app.whenReady().then(() => {
MainWindow.mainWindow.loadURL(this._getDeepLinkUrl(argv));
});
});
if (gotTheLock) {
app.whenReady().then(() => {
// Open main windows
MainWindow.openMainWindow();
MainWindow.mainWindow.loadURL(this._getDeepLinkUrl());
});
} else {
app.quit();
}
}
/**
* #description Create logic (OSX) for open url from protocol
*/
public static setProtocolHandlerOSX(): void {
app.on('open-url', (event: Electron.Event, url: string) => {
event.preventDefault();
app.whenReady().then(() => {
if (!isNil(url)) {
// Open main windows
MainWindow.openMainWindow();
MainWindow.mainWindow.loadURL(this._getUrlToLoad(url));
} else {
this._logInMainWindow({ s: 'URL is undefined', isError: true });
throw new Error('URL is undefined');
}
});
});
}
/**
* #description Format url to load in mainWindow
*/
private static _getUrlToLoad(url: string): string {
// Ex: url = myapp://deep-link/test?params1=paramValue
// Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
const splittedUrl = url.split('//');
// Generate URL to load in WebApp.
// Ex: file://path/index.html#deep-link/test?params1=paramValue
const urlToLoad = format({
pathname: Env.BUILDED_APP_INDEX_PATH,
protocol: 'file:',
slashes: true,
hash: `#${splittedUrl[1]}`,
});
return urlToLoad;
}
/**
* #description Resolve deep link url for Win32 or Linux from process argv
* #param argv: An array of the second instance’s (command line / deep linked) arguments
*/
private static _getDeepLinkUrl(argv?: string[]): string {
let url: string;
const newArgv: string[] = !isNil(argv) ? argv : process.argv;
// Protocol handler
if (process.platform === 'win32' || process.platform === 'linux') {
// Get url form precess.argv
newArgv.forEach((arg) => {
if (/myapp:\/\//.test(arg)) {
url = arg;
}
});
if (!isNil(url)) {
return this._getUrlToLoad(url);
} else if (!isNil(argv) && isNil(url)) {
this._logInMainWindow({ s: 'URL is undefined', isError: true });
throw new Error('URL is undefined');
}
}
}
And it's WORK :D

Media creation via php in Shopware 6

i'm struggling get a media import via PHP for Shopware 6 to work.
This is my service:
<?php declare(strict_types=1);
namespace My\Namespace\Service;
use Shopware\Core\Content\Media\File\MediaFile;
use Shopware\Core\Content\Media\MediaService;
use Shopware\Core\Framework\Context;
class ImageImport
{
/**
* #var MediaService
*/
protected $mediaService;
/**
* ImageImport constructor.
* #param MediaService $mediaService
*/
public function __construct(MediaService $mediaService)
{
$this->mediaService = $mediaService;
}
public function addImageToProductMedia($imageUrl, Context $context)
{
$mediaId = NULL;
$context->disableCache(function (Context $context) use ($imageUrl, &$mediaId): void {
$filePathParts = explode('/', $imageUrl);
$fileName = array_pop($filePathParts);
$fileNameParts = explode('.', $fileName);
$actualFileName = $fileNameParts[0];
$fileExtension = $fileNameParts[1];
if ($actualFileName && $fileExtension) {
$tempFile = tempnam(sys_get_temp_dir(), 'image-import');
file_put_contents($tempFile, file_get_contents($imageUrl));
$fileSize = filesize($tempFile);
$mimeType = mime_content_type($tempFile);
$mediaFile = new MediaFile($tempFile, $mimeType, $fileExtension, $fileSize);
$mediaId = $this->mediaService->saveMediaFile($mediaFile, $actualFileName, $context, 'product');
}
});
return $mediaId;
}
}
A entry in the table media with the correct media_folder_association is created. And as far as i can see there are no differences to other medias uploaded via backend (except private is 1 and user_id is NULL).
But in the backend the media entries are broken, seems like it can not load the actual image file (i've tried to set private to true to see it in the media section, same happens when adding the media to a product via php, but i guess the problem is before any assignment to products).
Image in backend media
Has anybody a suggestion whats wrong here?
Thanks
Phil
===== SOLUTION ======
Here is the updated and working service:
<?php declare(strict_types=1);
namespace My\Namespace\Service;
use Shopware\Core\Content\Media\File\FileSaver;
use Shopware\Core\Content\Media\File\MediaFile;
use Shopware\Core\Content\Media\MediaService;
use Shopware\Core\Framework\Context;
class ImageImport
{
/**
* #var MediaService
*/
protected $mediaService;
/**
* #var FileSaver
*/
private $fileSaver;
/**
* ImageImport constructor.
* #param MediaService $mediaService
* #param FileSaver $fileSaver
*/
public function __construct(MediaService $mediaService, FileSaver $fileSaver)
{
$this->mediaService = $mediaService;
$this->fileSaver = $fileSaver;
}
public function addImageToProductMedia($imageUrl, Context $context)
{
$mediaId = NULL;
$context->disableCache(function (Context $context) use ($imageUrl, &$mediaId): void {
$filePathParts = explode('/', $imageUrl);
$fileName = array_pop($filePathParts);
$fileNameParts = explode('.', $fileName);
$actualFileName = $fileNameParts[0];
$fileExtension = $fileNameParts[1];
if ($actualFileName && $fileExtension) {
$tempFile = tempnam(sys_get_temp_dir(), 'image-import');
file_put_contents($tempFile, file_get_contents($imageUrl));
$fileSize = filesize($tempFile);
$mimeType = mime_content_type($tempFile);
$mediaFile = new MediaFile($tempFile, $mimeType, $fileExtension, $fileSize);
$mediaId = $this->mediaService->createMediaInFolder('product', $context, false);
$this->fileSaver->persistFileToMedia(
$mediaFile,
$actualFileName,
$mediaId,
$context
);
}
});
return $mediaId;
}
}
In order to import files to Shopware 6 theres two steps which are necessary:
You have to create a media file object (MediaDefinition / media table). Take a look at the MediaConverter
Create a new entry in the SwagMigrationMediaFileDefinition (swag_migration_media_file table).
Each entry in the swag_migration_media_file table of the associated migration run will get processed by an implementation of MediaFileProcessorInterface.
To add a file to the table you can do something like this in your Converter class (this example is from the MediaConverter):
abstract class MediaConverter extends ShopwareConverter
{
public function convert(
array $data,
Context $context,
MigrationContextInterface $migrationContext
): ConvertStruct {
$this->generateChecksum($data);
$this->context = $context;
$this->locale = $data['_locale'];
unset($data['_locale']);
$connection = $migrationContext->getConnection();
$this->connectionId = '';
if ($connection !== null) {
$this->connectionId = $connection->getId();
}
$converted = [];
$this->mainMapping = $this->mappingService->getOrCreateMapping(
$this->connectionId,
DefaultEntities::MEDIA,
$data['id'],
$context,
$this->checksum
);
$converted['id'] = $this->mainMapping['entityUuid'];
if (!isset($data['name'])) {
$data['name'] = $converted['id'];
}
$this->mediaFileService->saveMediaFile(
[
'runId' => $migrationContext->getRunUuid(),
'entity' => MediaDataSet::getEntity(), // important to distinguish between private and public files
'uri' => $data['uri'] ?? $data['path'],
'fileName' => $data['name'], // uri or path to the file (because of the different implementations of the gateways)
'fileSize' => (int) $data['file_size'],
'mediaId' => $converted['id'], // uuid of the media object in Shopware 6
]
);
unset($data['uri'], $data['file_size']);
$this->getMediaTranslation($converted, $data);
$this->convertValue($converted, 'title', $data, 'name');
$this->convertValue($converted, 'alt', $data, 'description');
$albumMapping = $this->mappingService->getMapping(
$this->connectionId,
DefaultEntities::MEDIA_FOLDER,
$data['albumID'],
$this->context
);
if ($albumMapping !== null) {
$converted['mediaFolderId'] = $albumMapping['entityUuid'];
$this->mappingIds[] = $albumMapping['id'];
}
unset(
$data['id'],
$data['albumID'],
// Legacy data which don't need a mapping or there is no equivalent field
$data['path'],
$data['type'],
$data['extension'],
$data['file_size'],
$data['width'],
$data['height'],
$data['userID'],
$data['created']
);
$returnData = $data;
if (empty($returnData)) {
$returnData = null;
}
$this->updateMainMapping($migrationContext, $context);
// The MediaWriter will write this Shopware 6 media object
return new ConvertStruct($converted, $returnData, $this->mainMapping['id']);
}
}
swag_migration_media_files are processed by the right processor service. This service is different for documents and normal media, but it still is gateway dependent
=== DIFFERENT APPROACH (Shyim suggestion) ===
Take a look at this (taken from Shopwaredowntown's Github repository):
public function upload(UploadedFile $file, string $folder, string $type, Context $context): string
{
$this->checkValidFile($file);
$this->validator->validate($file, $type);
$mediaFile = new MediaFile($file->getPathname(), $file->getMimeType(), $file->getClientOriginalExtension(), $file->getSize());
$mediaId = $this->mediaService->createMediaInFolder($folder, $context, false);
try {
$this->fileSaver->persistFileToMedia(
$mediaFile,
pathinfo($file->getFilename(), PATHINFO_FILENAME),
$mediaId,
$context
);
} catch (MediaNotFoundException $e) {
throw new UploadException($e->getMessage());
}
return $mediaId;
}
src/Portal/Hacks/StorefrontMediaUploader.php:49
public function upload(UploadedFile $file, string $folder, string $type, Context $context): string

URL to code in node.js applications

I see they use this kind of code to call restful URLs.
Let's say we have /users/{userId}/tasks to create task for a user.
To call this they create another class instead of calling request directly as shown below:
MyAPP.prototype.users = function (userId) {
return {
tasks: function (taskId) {
return this.usersTasks(userId, taskId);
}
}
}
MyAPP.prototype.usersTasks = function (userId, taskId) {
return {
create: function (task, cb) {
make request POST call
}
}
}
Then we can call this as myapp.users('123').tasks().create(task, cb);
What is this kind of coding called and is there any way to automatically generate the code from the URL structure itself?
That is a way of making classes, but I suggest you look into ES6 classes
Defining a class :
class MyAPP {
//:called when created
constructor(name) {
this.name = name;
console.log("[created] MyAPP :",name);
//(a in memory database stored in MyAPP : for example purpose)
this.DB = {'user000':{'tasks':{'task000':'do pizza'},{'task001':'code some magik'}}}
}
//: Get specific taskID for userID
getTask(userID, taskID) {
console.log("[get task]",taskID,"[from user]",userID)
return (this.DB[userID][taskID])
}
//: Get all tasks for userID
allTasks(userID) {
console.log("[get all tasks from user]",userID)
return (this.DB[userID].tasks)
}
//: Create a taskID with taskContent for userID
newTask(userID, taskID, taskContent) {
this.DB[userID].tasks[taskID] = taskContent
}
}
Creating a MyAPP instance :
var myapp = new MyAPP('Pizza API'); //creates a MyAPP with a name
And then (maybe I got your question wrong) using express you would make a server and listen for requests (GET, POST, PUT, ...)
app.get("/APIv1/:userID/:actionID", function(req, res) {
switch(req.params.actionID){
case 'all':
res.send(myapp.allTasks(req.params.userID));
break
default :
res.send("The "+myapp.name+" doesn't support that (yet)")
break
}
});

Resources