I'm having a problem with Spatie Media Library. I created my class to use a different filesystem (specifically a Google bucket). Everything works smooth and I can integrate the filesystem correctly, save and view through the custom url. I created my class and gave what "Spatie" describes in its documentation as a namespace namespace Spatie\MediaLibrary\UrlGenerator;
. However, when I run the "artisan config: cache" command I get the error mentioned above.
Here my Custom Class Code extending BaseUrlGenerator:
namespace Spatie\MediaLibrary\UrlGenerator;
use DateTimeInterface;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Filesystem\FilesystemManager;
class GcsUrlGenerator extends BaseUrlGenerator
{
/** #var \Illuminate\Filesystem\FilesystemManager */
protected $filesystemManager;
public function __construct(Config $config, FilesystemManager $filesystemManager)
{
$this->filesystemManager = $filesystemManager;
parent::__construct($config);
}
/**
* Get the url for a media item.
*
* #return string
*/
public function getUrl(): string
{
$url = $this->getPathRelativeToRoot();
if ($root = config('filesystems.disks.'.$this->media->disk.'.root')) {
$url = $root.'/'.$url;
}
$url = $this->rawUrlEncodeFilename($url);
$url = $this->versionUrl($url);
return config('medialibrary.gcs.domain').'/'.$url;
}
/**
* Get the temporary url for a media item.
*
* #param \DateTimeInterface $expiration
* #param array $options
*
* #return string
*/
public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string
{
return $this
->filesystemManager
->disk($this->media->disk)
->temporaryUrl($this->getPath(), $expiration, $options);
}
/**
* Get the url for the profile of a media item.
*
* #return string
*/
public function getPath(): string
{
return $this->getPathRelativeToRoot();
}
/**
* Get the url to the directory containing responsive images.
*
* #return string
*/
public function getResponsiveImagesDirectoryUrl(): string
{
$url = $this->pathGenerator->getPathForResponsiveImages($this->media);
if ($root = config('filesystems.disks.'.$this->media->disk.'.root')) {
$url = $root.'/'.$url;
}
return config('medialibrary.gcs.domain').'/'.$url;
}
}
Here what I included in the published vendor of medialibrary
'custom_url_generator_class' => \Spatie\MediaLibrary\UrlGenerator\GcsUrlGenerator::class,
What I'm missing here?
Thanks for helping me
According to the documentation you should implement the Spatie\MediaLibrary\UrlGenerator interface, not the namespace. Alternatively you can extend Spatie\MediaLibrary\UrlGenerator\BaseUrlGenerator which implements that interface itself. So the namespace of your custom class should still adhere to default naming, meaning it should have namespacing according to the folder structure and classname so it gets autoloaded properly.
I just try to create my first extension about flowers with a list view and and a detail view. Now I want to add the possibility to browse through the flowers on detail view.
I found the following code Extbase Repository: findNext und findPrevious Funktionen
and added it to my repository
/**
* The repository for Pflanzens
*/
class PflanzenRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
protected $defaultOrderings = array(
'nameDeutsch' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);
/**
* Find next item by uid
* #param integer $uid The uid of the current record
* #return boolean|\TYPO3\CMS\Extbase\Persistence\Generic\QueryResult
*/
public function findNext($uid) {
$query = $this->createQuery();
$result = $query->matching($query->greaterThan('uid',$uid))->setLimit(1)->execute();
if($query->count()) {
return $result;
} else {
return false;
}
}
/**
* Find previous item by uid
* #param integer $uid The uid of the current record
* #return boolean|\TYPO3\CMS\Extbase\Persistence\Generic\QueryResult
*/
public function findPrev($uid) {
$query = $this->createQuery();
$ordering = array('uid'=>\TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING);
$result = $query->matching($query->lessThan('uid',$uid))->setLimit(1)->setOrderings($ordering)->execute();
if($query->count()) {
return $result;
} else {
return false;
}
}
}
This is my controller right now:
/**
* PflanzenController
*/
class PflanzenController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* pflanzenRepository
*
* #var \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository
* #inject
*/
protected $pflanzenRepository = NULL;
/**
* action list
*
* #return void
*/
public function listAction()
{
$pflanzens = $this->pflanzenRepository->findAll();
$this->view->assign('pflanzens', $pflanzens);
}
/**
* action show
*
* #param \TMRuebe\Faerbepflanzen\Domain\Model\Pflanzen $pflanzen
* #return void
*/
public function showAction(\TMRuebe\Faerbepflanzen\Domain\Model\Pflanzen $pflanzen)
{
$this->view->assign('pflanzen', $pflanzen);
}
}
Now I need help how to add the two public functions to the controller. And I also need a hint for the variable that I can use in my fluid template to create the previous link and the next link.
in showAction() you need to assign to further variables with the results of findNext() and findPrev().
$this->view->assign('previous', \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository::findPrev($pflanzen['uid']));
$this->view->assign('next', \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository::findNext($pflanzen['uid']));
in your detail template you need to build the links like the links in the list view.
You might build methods using the current object to get easier access to next and prev.
Question
Is it possible in Symfony 2.8+ / 3.x+ to dispatch event before starting entity validation?
Situation:
Let's say we have 100 entities, they have #LifeCycleCallbacks, they have #postLoad Event that do something, but the result of this is only used for valiation of Entity, in 99% of situations result of #postLoad is unimportant for system. So if we have hundrets or thousands of Entities fetched from DB there will be a lot of machine-cycles lose for unimportant data.
It would be nice to run some kind of event, that will run method, that will populate that data for that specific Entity, just before validations starts.
instead of:
$entity->preValidate();
$validator = $this->get('validator');
$errors = $validator->validate($entity);
we could have:
$validator = $this->get('validator');
$errors = $validator->validate($entity);
And in validate() situation, preValidate() will be dispatched autmaticly as Event (of course with check if Entity does have such method).
CaseStudy:
I have a system that stores pages/subpages as entities. There can be 10 or 10000 pages/subpages
Pages/subpages can have file.
Entities stores only files names (becouse we can't store SplFileInfo - resource serialization restriction)
While Entity->file property is type of string, when I want to make it to be instance of File (so we can do validation of type File) I have something like:
/**
* #postLoad()
*/
public function postLoad()
{
//magicly we get $rootPath
$this->file = new File($rootPath . '/' . $this->file);
}
/**
* #prePersist()
* #preUpdate()
*/
public function preSave()
{
if ($this->file instance of File)
$this->file = $this->file->getFilename();
}
}
Ok, but postLoad() will CHANGE the property, and Doctrine will NOTICE that. So in next
$entityManager->flush()
ALL entities will be flushed - even if preSave() will change it back to be just string as it was before.
So if I have any other entity, let's say TextEntity, and I want to remove it
$entityManager->remove($textEntity);
$entityManager->flush();
All other Entities that are somehow changed (change was noticed by Doctrine), are flushed, no matter if value of file property is the same as in DB (and change was only temporary).
It will be flushed.
So we have hundrets, or thousends of pointless sql updates.
Btw.
1. ->flush($textEntity) will throw Exception, becouse ->remove($textEntity) have already "deleted" that entity.
2. Entity property ->file must be of type File for Assert/File, becouse FileValidator can only accept values of File or absolute-path-to-file.
But I will NOT store absolute-path-to-file, becouse it will be completly different on Dev, Stage, and Production environments.
This is problem that occured when I tried to make file uploading as it was described in Symfony cookbook http://symfony.com/doc/current/controller/upload_file.html.
My solution was to, in postLoad(), create File instance in property that is not Doctrine column, and is anoted to have assertion, etc.
That works, but the problem of useless postLoad()s stays, and i thought about events. That could be elastic, and very elegant solution - instead of controllers getting "fat".
Any one have better solution? Or know how to dispatch event if ->validate() happends?
Hello Voult,
Edit: first method is deprecated in symfony 3 as the thread op mentioned in a comment. Check the second method made for symfony 3.
Symfony 2.3+,Symfony < 3
What I do in this cases, since symfony and most other bundles are using parameters for service class definition, is to extend that service. Check the example below and for more information on extending services check this link
http://symfony.com/doc/current/bundles/override.html
First you need to add a some marker to your entities that require pre-validation. I usually use interfaces for stuff like this something like
namespace Your\Name\Space;
interface PreValidateInterface
{
public function preValidate();
}
After this you extend the validator service
<?php
namespace Your\Name\Space;
use Symfony\Component\Validator\Validator;
class MyValidator extends Validator //feel free to rename this to your own liking
{
/**
* #inheritdoc
*/
public function validate($value, $groups = null, $traverse = false, $deep = false)
{
if (is_object($value) && $value instanceof PreValidateInterface) {
$value->preValidate();
}
return parent::validate($value, $groups, $traverse, $deep);
}
}
And final step, you need to add the class value parameter to your 'parameters' config block in config.yml, something like this:
parameters:
validator.class: Your\Name\Space\MyValidator
This is the basic idea. Now you can mix end match this idea with whatever you want to achieve. For instance instead of calling a method on the entity (I usually like to keep business logic outside of my entities), you can look for the interface and if it is there you can launch a pre.validate event with that entity on it, and use a listener to do the job. After that you can keep the result from parent::validate and also launch a post.validate event. You see where i'm going with this. You basically can do whatever you like now inside that validate method.
PS: The example above is the easy method. If you want to go the event route, the service extension will be harder, since you need to inject the dispatcher into it. Check the link I provided at the beginning to see the other way to extend a service and let me know if you need help with this.
For Symfony 3.0 -> 3.1
In this case they managed to make it hard and dirtier to extend
Step 1:
Create your own validator something like this:
<?php
namespace Your\Name\Space;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception;
use Symfony\Component\Validator\MetadataInterface;
use Symfony\Component\Validator\Validator\ContextualValidatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class myValidator implements ValidatorInterface
{
/**
* #var ValidatorInterface
*/
protected $validator;
/**
* #param ValidatorInterface $validator
*/
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
/**
* Returns the metadata for the given value.
*
* #param mixed $value Some value
*
* #return MetadataInterface The metadata for the value
*
* #throws Exception\NoSuchMetadataException If no metadata exists for the given value
*/
public function getMetadataFor($value)
{
return $this->validator->getMetadataFor($value);
}
/**
* Returns whether the class is able to return metadata for the given value.
*
* #param mixed $value Some value
*
* #return bool Whether metadata can be returned for that value
*/
public function hasMetadataFor($value)
{
return $this->validator->hasMetadataFor($value);
}
/**
* Validates a value against a constraint or a list of constraints.
*
* If no constraint is passed, the constraint
* {#link \Symfony\Component\Validator\Constraints\Valid} is assumed.
*
* #param mixed $value The value to validate
* #param Constraint|Constraint[] $constraints The constraint(s) to validate
* against
* #param array|null $groups The validation groups to
* validate. If none is given,
* "Default" is assumed
*
* #return ConstraintViolationListInterface A list of constraint violations.
* If the list is empty, validation
* succeeded
*/
public function validate($value, $constraints = null, $groups = null)
{
//the code you are doing all of this for
if (is_object($value) && $value instanceof PreValidateInterface) {
$value->preValidate();
}
//End of code
return $this->validator->validate($value, $constraints, $groups);
}
/**
* Validates a property of an object against the constraints specified
* for this property.
*
* #param object $object The object
* #param string $propertyName The name of the validated property
* #param array|null $groups The validation groups to validate. If
* none is given, "Default" is assumed
*
* #return ConstraintViolationListInterface A list of constraint violations.
* If the list is empty, validation
* succeeded
*/
public function validateProperty($object, $propertyName, $groups = null)
{
$this->validator->validateProperty($object, $propertyName, $groups);
}
/**
* Validates a value against the constraints specified for an object's
* property.
*
* #param object|string $objectOrClass The object or its class name
* #param string $propertyName The name of the property
* #param mixed $value The value to validate against the
* property's constraints
* #param array|null $groups The validation groups to validate. If
* none is given, "Default" is assumed
*
* #return ConstraintViolationListInterface A list of constraint violations.
* If the list is empty, validation
* succeeded
*/
public function validatePropertyValue($objectOrClass, $propertyName, $value, $groups = null)
{
$this->validator->validatePropertyValue($objectOrClass, $propertyName, $value, $groups);
}
/**
* Starts a new validation context and returns a validator for that context.
*
* The returned validator collects all violations generated within its
* context. You can access these violations with the
* {#link ContextualValidatorInterface::getViolations()} method.
*
* #return ContextualValidatorInterface The validator for the new context
*/
public function startContext()
{
$this->validator->startContext();
}
/**
* Returns a validator in the given execution context.
*
* The returned validator adds all generated violations to the given
* context.
*
* #param ExecutionContextInterface $context The execution context
*
* #return ContextualValidatorInterface The validator for that context
*/
public function inContext(ExecutionContextInterface $context)
{
$this->validator->inContext($context);
}
}
Step 2:
Extend Symfony\Component\Validator\ValidatorBuilder something like this:
namespace Your\Name\Space;
use Symfony\Component\Validator\ValidatorBuilder;
class myValidatorBuilder extends ValidatorBuilder
{
public function getValidator()
{
$validator = parent::getValidator();
return new MyValidator($validator);
}
}
You need to override Symfony\Component\Validator\Validation. This is the ugly/dirty part, because this class is final so you can't extend it, and has no interface to implement, so you will have to pay attention to in on future versions of symfony in case backward compatibility is broken. It goes something like this:
namespace Your\Name\Space;
final class MyValidation
{
/**
* The Validator API provided by Symfony 2.4 and older.
*
* #deprecated use API_VERSION_2_5_BC instead.
*/
const API_VERSION_2_4 = 1;
/**
* The Validator API provided by Symfony 2.5 and newer.
*/
const API_VERSION_2_5 = 2;
/**
* The Validator API provided by Symfony 2.5 and newer with a backwards
* compatibility layer for 2.4 and older.
*/
const API_VERSION_2_5_BC = 3;
/**
* Creates a new validator.
*
* If you want to configure the validator, use
* {#link createValidatorBuilder()} instead.
*
* #return ValidatorInterface The new validator.
*/
public static function createValidator()
{
return self::createValidatorBuilder()->getValidator();
}
/**
* Creates a configurable builder for validator objects.
*
* #return ValidatorBuilderInterface The new builder.
*/
public static function createValidatorBuilder()
{
return new MyValidatorBuilder();
}
/**
* This class cannot be instantiated.
*/
private function __construct()
{
}
}
And last step overwrite the parameter validator.builder.factory.class in your config.yml:
parameters:
validator.builder.factory.class: Your\Name\Space\MyValidation
This is the least invasive way to do it, that i can find. Is not that clean and it could need some maintaining when you upgrade symfony to future versions.
Hope this helps, and happy coding
Alexandru Cosoi
I'm building a laravel app using Sentinel, based in an old system code in Yii.
Purpose is be able to login in new system with old users / old db.
I first has to resolved model issue:
Custom Model and fields with Sentinel / Laravel
Now, it is ok.
I have a last issue, it seems to be hashing password from different ways.
When I check the hash method in Yii, I can find that it use Blowfish algorithm:
/**
* CPasswordHelper provides a simple API for secure password hashing and verification.
*
* CPasswordHelper uses the Blowfish hash algorithm available in many PHP runtime
* environments through the PHP {#link http://php.net/manual/en/function.crypt.php crypt()}
* built-in function. As of Dec 2012 it is the strongest algorithm available in PHP
* and the only algorithm without some security concerns surrounding it. For this reason,
* CPasswordHelper fails to initialize when run in and environment that does not have
* crypt() and its Blowfish option. Systems with the option include:
* (1) Most *nix systems since PHP 4 (the algorithm is part of the library function crypt(3));
* (2) All PHP systems since 5.3.0; (3) All PHP systems with the
* {#link http://www.hardened-php.net/suhosin/ Suhosin patch}.
* For more information about password hashing, crypt() and Blowfish, please read
* the Yii Wiki article
* {#link http://www.yiiframework.com/wiki/425/use-crypt-for-password-storage/ Use crypt() for password storage}.
* and the
* PHP RFC {#link http://wiki.php.net/rfc/password_hash Adding simple password hashing API}.
*
* CPasswordHelper throws an exception if the Blowfish hash algorithm is not
* available in the runtime PHP's crypt() function. It can be used as follows
*
In the other hand, Sentinel manage several hash methods:
Native hasher
Bcrypt hasher
Callback hasher
Whirlpool hasher
SHA256 hasher
So, I guessed the common method was bcrypt, and in my Laravel model I did:
class Administrador extends EloquentUser {
protected $table = 'administrador';
protected $fillable = [];
protected $primaryKey = 'administradorid';
protected $loginNames = ['correo'];
protected $guarded = ['administradorid'];
protected $hidden = ['contrasena', 'remember_token'];
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* Set the Sentry User Model Hasher to be the same as the configured Sentry Hasher
*/
public static function boot()
{
parent::boot();
Sentinel::setHasher(new BcryptHasher);
}
}
So really, I don't really know what to do to solve it....
What you can do to support both systems at this time is create an implementation of the Cartalyst\Sentinal\Hashing\HasherInterface like this for example:
use Cartalyst\Sentinel\Hashing\HasherInterface;
class CombinedHasher implements HasherInterface
{
/**
* #var HasherInterface
*/
private $primary;
/**
* #var HasherInterface
*/
private $fallback;
/**
* #param HasherInterface $primary
* #param HasherInterface $fallback
*/
public function __construct(HasherInterface $primary, HasherInterface $fallback)
{
$this->primary = $primary;
$this->fallback = $fallback;
}
/**
* Hash the given value.
*
* #param string $value
* #return string
* #throws \RuntimeException
*/
public function hash($value)
{
return $this->primary->hash($value);
}
/**
* Checks the string against the hashed value.
*
* #param string $value
* #param string $hashedValue
* #return bool
*/
public function check($value, $hashedValue)
{
if ($this->primary->check($value, $hashedValue)) {
return true;
}
return $this->fallback->check($value, $hashedValue);
}
}
As you can see it takes two instances of the HasherInterface. So in this case you would inject the new implementation you want you use first and then create an implementation of the interface which implements the hashing algorithm Yii is using.
While checking the hash it will first use the new hashing algorithm. If this returns false it will also check using the fallback (Yii algorithm). To create hashes it will only use the new hashing algorithm. (You might want to change this for development however you should not develop using the production database anyways.)
So what you have to do next is create an implementation of the HasherInterface which will use the hashing algorithm Yii is using:
use Cartalyst\Sentinel\Hashing\HasherInterface;
class YiiHasher implements HasherInterface
{
/**
* Hash the given value.
*
* #param string $value
* #return string
* #throws \RuntimeException
*/
public function hash($value)
{
// You'll have to implement this
return yiiHasher($value);
}
/**
* Checks the string against the hashed value.
*
* #param string $value
* #param string $hashedValue
* #return bool
*/
public function check($value, $hashedValue)
{
// You'll have to implement this
return yiiHashChecker($value, $hashedValue);
}
}
You'll have to check whether Yii has a package for this or you'll have to check their source code to see how it works.
So to use this you would create an instance of the CombinedHasher like this:
use Cartalyst\Sentinel\Hashing\BcryptHasher;
use Namespace\For\Your\YiiHasher;
$primary = new BcryptHasher();
$fallback = new YiiHasher();
$hasher = new CombinedHasher($primary, $fallback);
Update 1: Extra info from the documentation
After actually reading through their documentation I noticed they also provide a CallbackHasher which might be less work to set up: https://cartalyst.com/manual/sentinel/2.0#callback-hasher
They also recommend using the NativeHasher over the BcryptHasher: https://cartalyst.com/manual/sentinel/2.0#native-hasher
Update 2: Where to set up
You could for example create them in app/Hashing. Then you'd have to make sure they have the namespace App\Hashing.
To set this up you can use your AppServiceProvider which is located in app/Providers/AppServiceProvider.php.
// Import the classes on the top
use App\Hashing\CombinedHasher;
use App\Hashing\YiiHasher;
use Cartalyst\Sentinel\Hashing\NativeHasher;
// In the AppServiceProvider class itself
public function boot()
{
$hasher = $this->app['Cartalyst\Sentinel\Hashing\HasherInterface'];
Sentinel::setHasher($hasher);
}
public function register()
{
$this->app->singleton('Cartalyst\Sentinel\Hashing\HasherInterface', function($app) {
$primary = new NativeHasher();
$secondary = new YiiHasher();
return new CombinedHasher($primary, $secondary);
});
}
I am upgrading my site from an old version of codeigniter to new one but I got an error "Cannot access protected property CI_Output::enable_profiler" during upgrade. I know that the property enable_profiler has been protected in new versions. But I do not know how can I access this property in my controller/model. I do not want to change my existing code. Following is my code
if($this->output->enable_profiler)
{
.......
}
Please read the CI doc you can use the following method to enable disable profiling
$this->output->enable_profiler(TRUE);// to enable
$this->output->enable_profiler(FALSE); // to disable
profiling
The return type is void for $this->output->enable_profiler(FALSE); In class CI_Output
/**
* Enable/disable Profiler
*
* #access public
* #param bool
* #return void
*/
function enable_profiler($val = TRUE)
{
$this->enable_profiler = (is_bool($val)) ? $val : TRUE;
return $this;
}