Ive tried a number of solutions and have not found anything that works.
My base directory for all files is localhost/manpower
I put this in my webpack...
let mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/assets/js/app.js', 'public/assets/js')
.sass('resources/assets/sass/app.scss', 'public/assets/css')
.sass('resources/assets/sass/header.scss', 'public/assets/css')
.version();
When I use the ~ for the home, the processing of the CSS just removes the ~
mix.setPublicPath('manpower/public');
Just creates a directory under the existing file structure and puts the files in that. Unfortunately this popular solution does not change the output of the final CSS.
No mater what I try, I can't get it to add 'manpower' to the URL's I put in the SCCS!
Posting my config to help you, I think that you forgot to define the alias, I have my config in two files to help the IDE (PHPStorm) recognize the ~
(solution from this answer https://stackoverflow.com/a/50159420/5458355)
// webpack.config.js
const path = require('path')
const webpack = require('webpack')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
module.exports = {
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'~': path.resolve(__dirname, './resources/assets/js')
}
},
output: {
path: process.env.MIX_APP_URL, <--- var from .env
publicPath: '/Socse.GST/public/',
chunkFilename: 'dist/js/chunk.[name].js'
}
}
// webpack.mix.js
const path = require('path')
const mix = require('laravel-mix')
const webpack = require('webpack')
mix
.js('resources/assets/js/app.js', 'public/dist/js')
.sass('resources/assets/sass/app.scss', 'public/dist/css')
.styles([
'resources/assets/sass/fa/css/fontawesome-all.css',
'public/css/awesome-bootstrap-checkbox.css',
'public/css/inspinia.css',
'node_modules/vue-multiselect/dist/vue-multiselect.min.css'
], 'public/dist/css/all.css')
.sourceMaps()
//.disableNotifications()
if (mix.inProduction()) {
mix.version()
}
mix.webpackConfig({
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
})
],
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'~': path.join(__dirname, './resources/assets/js')
}
},
output: {
chunkFilename: 'dist/js/chunk.[name].[chunkhash].js',
path: process.env.MIX_APP_URL,
publicPath: '/wms/public/'
}
})
New version
const path = require('path');
const mix = require('laravel-mix');
const webpack = require('webpack');
mix
.js('resources/assets/js/app.js', 'assets/js')
.sass('resources/assets/sass/app.scss', 'assets/css')
.sass('resources/assets/sass/header.scss', 'assets/css')
.version()
.options({
processCssUrls: true
});
if (mix.inProduction()) {
mix.version()
}
mix.webpackConfig({
resolve: {
alias: {
'~': path.join(__dirname, './resources/')
}
},
output: {
chunkFilename: 'dist/js/chunk.[name].[chunkhash].js',
path: process.env.MIX_APP_URL,
publicPath: '/public/'
}
})
Im pretty sure this is a problem with the webpack.config.js
Ive been able to resolve some of the issues but the error remains.
/**
* As our first step, we'll pull in the user's webpack.mix.js
* file. Based on what the user requests in that file,
* a generic config object will be constructed for us.
*/
let mix = require('../index');
let ComponentFactory = require('../components/ComponentFactory');
new ComponentFactory().installAll();
require(Mix.paths.mix());
/**
* Just in case the user needs to hook into this point
* in the build process, we'll make an announcement.
*/
Mix.dispatch('init', Mix);
/**
* Now that we know which build tasks are required by the
* user, we can dynamically create a configuration object
* for Webpack. And that's all there is to it. Simple!
*/
let WebpackConfig = require('../src/builder/WebpackConfig');
//module.exports = new WebpackConfig().build();
const path = require('path')
const webpack = require('webpack')
module.exports = {
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'~': path.resolve(__dirname, './resources/assets/js')
},
},
output: {
path: process.env.MIX_APP_URL,
publicPath: '/manpower/public/',
chunkFilename: 'dist/js/chunk.[name].js'
}
}
You may want to provide your version of mix and sass-loader (there is a bug in old sass-loader that does not work with tilde). Also, please do not post comment as update, it causes confusions in your question.
Generally, avoid using tilde; instead, use relative path. You want to look at this answer: https://stackoverflow.com/a/33972875/2188545
Even without all the confusing comments, tilde is confusing when use in url, especially when your browser path manpower/ is not a simple root / path. Don't get me wrong, tilde is fine with css import as it is generally resolve during compilation; just more confusing when use in url. Also, please use quote around your css url.
Related
My symfony 5.4 project uses aws_s3 + flysystem + liip_imagine.
In aws_s3, I have a PRIVATE bucket: "myBucket" with 3 subfolders :
documents
photos
media
And IAM PERMISSION
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetObject",
"s3:DeleteObject",
"s3:GetObjectAcl",
"s3:PutObjectAcl",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::myBucket",
"arn:aws:s3:::mybucket/*"
]
My setups :
see : https://github.com/liip/LiipImagineBundle/issues/823
Service.yaml
...
parameters:
uploads_base_url: '%env(AWS_S3_UPLOAD_BASE_URL)%'
services :
Aws\S3\S3Client:
arguments:
-
version: '2006-03-01'
region: '%env(AWS_S3_ACCESS_REGION)%'
credentials:
key: '%env(AWS_S3_ACCESS_ID)%'
secret: '%env(AWS_S3_ACCESS_SECRET)%'
oneup_flysystem.yaml
...
adapters:
aws_s3_adapter:
awss3v3:
client : Aws\S3\S3Client
bucket: '%env(AWS_S3_BUCKET_NAME)%'
options:
ACL: bucket-owner-full-control
filesystems:
aws_s3_system:
adapter: aws_s3_adapter
lipp_imagine.yaml
# https://symfony.com/bundles/LiipImagineBundle/current/cache-resolver/aws_s3.html
# I do not understand everything
...
driver: "gd"
loaders:
aws_s3_loader:
flysystem:
filesystem_service: oneup_flysystem.aws_s3_system_filesystem
data_loader: aws_s3_loader
resolvers:
aws_s3_resolver:
flysystem:
filesystem_service: oneup_flysystem.aws_s3_system_filesystem
root_url: '%uploads_base_url%'
cache_prefix: media/cache
cache: aws_s3_resolver
filter_sets:
squared_thumbnail_small:
quality: 70
filters:
thumbnail:
size: [50, 50]
mode: outbound
twig
# call twig_function assetPresigned
<a href="{{ assetPresigned('photos', player.photoFilename) }}" target="_blank">
<img src="{{ assetPresigned('photos', player.photoFilename ) | imagine_filter('squared_thumbnail_small') }}" alt="photo">
</a>
FileUploadService.php
public function assetPresigned(string $folder, string $filename): string
{
$command = $this->s3Client->getCommand('GetObject', [
'Bucket' => $this->awsS3BucketName,
'Key' => $folder.'/'.$filename,
]);
// RETURN PRESIGNED URL
$urlPresigned = $this->s3Client->createPresignedRequest($command, '+5 minutes');
return ((string) $urlPresigned->getUri());
}
pb 1 :
My problem is that the "squared_thumbnail_small" filter rewrites the url removing the pre-signed signature
results in twig :
href: the image appears on the click because url is pre-signed
img: url loses its signature and therefore is not displayed
nb: it is liip_imagine via "imagine_filter('squared_thumbnail_small) which creates the thumbnail in mybucket/media. At this stage, the thumbnail does not yet appear in mybucket/media because because it has not yet been displayed
question :
How to properly configure my code so that the filter does not remove the presigned signature ?
Here is what I tried
FileUploadService.php -
namespace App\Service;
...
public function assetPresigned(string $folder, string $filename): string
{
# call ImagineFilterService.php
$this->imagineFilter->filter($folder.'/'.$filename);
# ...
$command....
}
ImagineFilterService.php
namespace App\Service;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Liip\ImagineBundle\Imagine\Data\DataManager;
use Liip\ImagineBundle\Imagine\Filter\FilterManager;
use App\Service\FileUploadService;
# https://symfony.com/bundles/LiipImagineBundle/current/filters.html#dynamic-filters
# I tried to create a filter dynamically based on this documentation
Class ImagineFilterService
public function filter($path)
{
$filter = 'squared_thumbnail_small';
# if photo is not stored in myBucket/media then you save it by applying the filter?
if (!$this->cacheManager->isStored($path, $filter)) {
$binary = $this->dataManager->find($filter, $path);
$filteredBinary = $this->filterManager->applyFilter($binary, $filter);
# In this method, I pass in parameter the resolver
$this->cacheManager->store($filteredBinary, $path, $filter, 'aws_s3_resolver');
}
// ERROR 403!!!
return $this->cacheManager->resolve($path, $filter);
}
I now recover the thumbnails that were already stored in myBucket/media (ok)
But for saving new thumbnails in myBucket/media I got a 403 error.
AWS HTTP error: Client error: PUT resulted in a 403 Forbidden` response:
Access Denied
So I lose the credentials.
This is complex for me and a precise answer (see a piece of code) would help me a lot. I don't know where I'm wrong. I've been stuck for several days
Thanks for your help.
I'm using FMElfinder in association with TinyMCE for managing the assets (images, pdf ...) of the users (managed with FOSUSerBundle)
I've seen that this tool can handle multiple root folder, but in my case, it isn't quite usable : i would like to have a root folder for each user.
In the configuration file app/config/config.yml, there is the root path(s) defined :
fm_elfinder:
instances:
default:
locale: %locale%
...
connector:
roots:
uploads:
driver: LocalFileSystem
path: uploads/data
I was thining about "simply" changing the path to something like :
path: uploads/data/{the_username}
where the username would be the username of the currently logged user
In a controller i can do
$user = $this->get('security.token_storage')->getToken()->getUser();
$username = $user->getUsername();
But i don't know if it's possible (and if so, how) to access specifically the username of the logged user into a config file
Thank you if you have any suggestion
=================[EDIT] ==========================================
I've use the override of configuration. I think i followed the steps, but i haven't managed to make it work :
1 - Create the class
use FM\ElfinderBundle\Model\ElFinderConfigurationProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ElfinderConfigurator implements ElFinderConfigurationProviderInterface
{
protected $container;
protected $options;
/**
* #param ContainerInterface $container
*/
public function __construct($options, ContainerInterface $container)
{
$this->container = $container;
$this->storage = $container->get('security.token_storage');
$this->options = $options;
}
/**
* #param $instance
*
* #return array
*/
public function getConfiguration($instance)
{
//retrieve basepath
$basepath_abs = $this->container->get('kernel')->getRootDir()."/../web/uploads";
$basepath = "uploads/data";
//define path for user
$userid = $this->storage->getToken()->getUser()->getId();
$root = $basepath.'/'.$userid;
$this->options['instances']['default']['connector']['roots']['uploads']['path'] = $root.'/root';
$this->options['instances']['default']['connector']['roots']['uploads']['upload_max_size'] = '2M';
$option = [
'corsSupport' => false,
'roots' => $this->options['instances']['default']['connector']['roots'],
];
$root_abs = $basepath_abs.'/data/'.$userid;
//creates dir if not available
if (!is_dir($root_abs)) {
mkdir($root_abs.'/root', 0775, true);
}
return $option;
}
}
2 - Set my service :
myvendor.mybundle.elfinder_configurator:
class: Myvendor\Mybundle\Services\ElfinderConfigurator
arguments: ["%fm_elfinder%", "#service_container"]
3 - Call the service in app/config/config.yml
fm_elfinder:
configuration_provider: myvendor.mybundle.elfinder_configurator
...
It works partially : When i open the elfinde, the directory are correctly created if they don't exists. But there must be a path problem, and i'm not sure it's well overriden because :
- The thumbs are not displayed in elfinder
- When i add the image to the editor, i don't have the correct path of the image, i have :
//app_dev.php/efconnect?cmd=file&target=l1_Q2FwdHVyZSBkJ8OpY3JhbiBkZSAyMDE2LTAxLTI0IDE0OjM2OjI0LnBuZw
instead of the actual path of the image (if i don't use the override, the tool works and gives me this path)
../../../../uploads/data/1/root/img1.png
and no image is displayed.
Also, if i look in the js console for the
efconnect?cmd=open&target=&init=1&tree=1&_=1469377765664
I see that uplMaxSize is 200M,
in any case, there is no js error in the console
I think you are looking for a custom config provider:
https://github.com/helios-ag/FMElfinderBundle/blob/master/Resources/doc/advanced-configuration.md#custom-configuration-provider
You could then inject the token storage into the service and fetch the user from
like in any controller:
services:
my_elfinder_configurator:
class: Acme\DemoBundle\elFinder\UserAwareConfigurator
arguments: ["#token_storage", "%any_container_params%"]
I'm using Symfony3 with the KnpGaufretteBundle to connect to an Amazon S3 bucket with the AWS S3 method outlined on their Github Readme
aws_s3_adapter:
key: "%aws_key%"
secret_key: "%aws_secret%"
region: "%aws_region%"
knp_gaufrette:
adapters:
images:
aws_s3:
service_id: 'aws_s3_adapter.client'
bucket_name: '%aws_bucket%'
options:
directory: 'images'
filesystems:
images:
adapter: images
alias: images_fs
I also have a service defined that I want to use to manage this filesystem (and others) with.
Definition:
services:
test.image_manager:
class: TestBundle\Filesystem\FileManager
arguments:
filesystem: "#images_fs"
filesystem_name: "images"
mimetypes: ["image/jpeg", "image/png", "image/gif"]
Class:
<?php
namespace TestBundle\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Gaufrette\Filesystem;
use Gaufrette\StreamWrapper;
class FileManager
{
private $allowedMimeTypes;
private $filesystem;
private $filsystem_name;
public function __construct(Filesystem $filesystem, $filesystem_name, $mimetypes = array())
{
$this->filesystem = $filesystem;
$this->filesystem_name = $filesystem_name;
$this->allowedMimeTypes = $mimetypes;
}
public function upload(UploadedFile $file, $filename)
{
// Check if the file's mime type is in the list of allowed mime types.
if (!in_array($file->getClientMimeType(), $this->allowedMimeTypes)) {
throw new \InvalidArgumentException(sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
}
$adapter = $this->filesystem->getAdapter();
$adapter->setMetadata($filename, array('contentType' => $file->getClientMimeType()));
return $adapter->write($filename, file_get_contents($file->getPathname()));
}
public function fetch( $filename )
{
if( ! $this->filesystem->has( $filename ) )
{
return false;
}
/* -- PROBLEM -- */
StreamWrapper::register();
return new BinaryFileResponse( "gaufrette://{$this->filesystem_name}/{$filename}" );
/* -- PROBLEM -- */
}
public function delete( $filename )
{
if( ! $this->filesystem->has( $filename ) )
{
return false;
}
return $this->filesystem->delete( $filename );
}
}
I'm able to upload successfully to the bucket using the upload function, telling me that the filesystem exists and is working properly.
I am not, however, able to use the Gaufrette\StreamWrapper to serve the file using a BinaryFileResponse as it says I should do. Instead it is giving me the error that I put in the title: There is no filesystem defined for the "images" domain.
The filesystem definitely exists, as I'm using it to upload the images. Any clues as to what the problem might be that's preventing me from using that filesystem would be very helpful. The Gaufrette documentation is really sparse online so far as I've found, but I'm going to keep digging.
Looking at MainConfiguration.php showed that there's a steam_wrapper option in the configuration for the bundle. I added this into my config.yml under where the filesystems are defined like so:
knp_gaufrette:
adapters:
images:
aws_s3:
service_id: 'aws_s3_adapter.client'
bucket_name: '%aws_bucket%'
options:
directory: 'images'
.
.
.
filesystems:
images:
adapter: images
alias: images_fs
.
.
.
stream_wrapper:
filesystems: [ images, ... ]
and the above code now works.
I'm having the same problem symfony2 is describing here
This comes in handy when you have a bundle but don't want to manually
add the routes for the bundle to app/config/routing.yml. This may be
especially important when you want to make the bundle reusable
TLDR; im trying to implement a custom Route Loader using this part of the symfony2 documentation
http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html#more-advanced-loaders
However it doesn't seem to be working, the route cannot be found;
This is what I've tried so far:
The loader:
<?php
//namespace Acme\DemoBundle\Routing;
namespace Gabriel\AdminPanelBundle\Routing;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;
class AdvancedLoader extends Loader
{
public function load($resource, $type = null)
{
$collection = new RouteCollection();
$resource = '#GabrielAdminPanelBundle/Resources/config/routing.yml';
$type = 'yaml';
$importedRoutes = $this->import($resource, $type);
$collection->addCollection($importedRoutes);
return $collection;
}
public function supports($resource, $type = null)
{
return $type === 'advanced_extra';
}
}
here is my routing.yml
located in: src/Gabriel/AdminPanelBundle/Resources/config/routing.yml
the routing.yml
gabriel_admin_panel:
resource: "#GabrielAdminPanelBundle/Controller/"
type: annotation
prefix: /superuser
The Routes of the bundle can't be found unless I put the Routes back in the main app/config/routing.yml file, how to fix this?
Edit:
FileLoaderImportCircularReferenceException: Circular reference
detected in "/app/config/routing_dev.yml"
("/app/config/routing_dev.yml" > "/app/config/routing.yml" > "." >
"#GabrielAdminPanelBundle/Controller/" >
"/app/config/routing_dev.yml").
You must also configure service
# src/Gabriel/AdminPanelBundle/Resources/config/services.yml
your_bundle.routing_loader:
class: Gabriel\AdminPanelBundle\Routing\AdvancedLoader
tags:
- { name: routing.loader }
And routing file
# app/config/routing.yml
YourBundle_extra:
resource: .
type: advanced_extra
I'm trying to write a symfony 2 functional test. This is my code:
<?php
namespace WebSite\MainBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ProductControllerTest extends WebTestCase
{
public function testPageContents()
{
$domCategoryLinksExpr = '.catalog-col-block > ul > li > a';
$client = static::createClient();
$crawler = $client->request('GET', '/catalog/');
$this->assertTrue($client->getResponse()->getStatusCode() == '200');
$countCategories = $crawler->filter($domCategoryLinksExpr)->count();
$this->assertTrue($crawler->filter($domCategoryLinksExpr)->count() > 0);
$categoryLink = $crawler->filter($domCategoryLinksExpr)->eq(rand(1, $countCategories))->link();
$crawler = $client->click($categoryLink);
}
}
But when i run this test:
phpunit -c app src/WebSite/MainBundle/Tests/Controller/
I got this:
1) WebSite\MainBundle\Tests\Controller\ProductControllerTest::testPageContents
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /app_dev.php/catalog/psp"
...
/app_dev.php/catalog/psp is the dynamic value of $categoryLink->getUri(). And
this route exists and correctly works in web browser. Any ideas?
UPD:
This is my routing rules:
routing_dev.yml:
...
_main:
resource: routing.yml
....
routing.yml:
....
WebSiteCategoryBundle:
resource: "#WebSiteCategoryBundle/Controller/"
type: annotation
prefix: /
....
src/WebSite/CategoryBundle/CategoryController.php:
/**
* #Route("/catalog")
*/
class CategoryController extends Controller
{
/**
* #Route("/{alias}", name="show_category" )
* #Template()
*/
public function showAction( $alias )
{
// some action here
}
}
It works fine in browser, but seems like $crowler does`not see this annotation rules.
UPD2: The problem was in "routing_test.yml" which missing in Symfony 2 standard edition.
So I create it:
routing_test.yml:
_main:
resource: routing_dev.yml
and exception disappear. Thanks to all.
It would be nice if you posted your routing.yml
You can also take a look at:
http://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/annotations/routing.html
You can use routing annotation at your actions.
To solve your problem I would like to see your routing config.
echo $client->getResponse()->getContent() will help you with debugging (even there is an exception). It will output html of the request.
It looks like your route does not exist and might be in wrong location (wrong environment specified?)