Giter Site home page Giter Site logo

rdohms / dms-filter-bundle Goto Github PK

View Code? Open in Web Editor NEW
77.0 5.0 24.0 323 KB

Provides a FilterService for Symfony to allow users to implement input filtering in entities using Annotations

License: MIT License

PHP 100.00%
symfony symfony-bundle filtering hacktoberfest

dms-filter-bundle's Introduction

DMS Filter Bundle

This bundle makes DMS/Filter available for use in your application for input filtering.

Current Status: Build Status Dependency Status

Install

1. Import libraries

Option A) Use Composer.

composer require dms/dms-filter-bundle

2. Enable Bundle

Add this to your AppKernel.php

new DMS\Bundle\FilterBundle\DMSFilterBundle(),

3. Configure

This bundle can now automatically filter your forms if it finds a annotated entity attached.

This is the default behaviour, if you want to disable it add this to your config.yml

dms_filter:
    auto_filter_forms: false

Usage

Adding Annotations

To add annotations to your entity, import the namespace and add them like this:

<?php

namespace App\Entity;

//Import Annotations
use DMS\Filter\Rules as Filter;

class User
{

    /**
    * @Filter\StripTags()
    * @Filter\Trim()
    * @Filter\StripNewlines()
    *
    * @var string
    */
    public $name;

    /**
    * @Filter\StripTags()
    * @Filter\Trim()
    * @Filter\StripNewlines()
    *
    * @var string
    */
    public $email;

}

Manual Filtering

Use the dms.filter service along with annotations in the Entity to filter data.

public function indexAction()
{

    $entity = new \Acme\DemoBundle\Entity\SampleEntity();
    $entity->name = "My <b>name</b>";
    $entity->email = " [email protected]";

    $oldEntity = clone $entity;

    $filterService = $this->get('dms.filter');
    $filterService->filterEntity($entity);

    return array('entity' => $entity, "old" => $oldEntity);
}

Auto filtering

This bundle can now automatically filter your forms if it finds a annotated entity attached. If enabled entities will be filtered before they are validated.

Cascade Filtering

This Bundle automatically cascades filtering into all embedded forms that return valid entities. If you wish child entities to be ignored, set the cascade_filter option on the form to false.

class TaskType extends AbstractType
{
    // ...

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'cascade_filter' => false,
            ));
    }

    // ...
}

Service based method

If you need to filter content using a method in a service, you do not need to create your own Annotations, you can simply use the Service Filter, designed specifically for Symfony Services.

See below the usage example of the annotation, it takes 2 options: service and method.

<?php

namespace App\Entity;

//Import Annotations
use DMS\Filter\Rules as Filter;

//Import Symfony Rules
use DMS\Bundle\FilterBundle\Rule as SfFilter;

class User
{
    /**
    * @Filter\StripTags()
    * @SfFilter\Service(service="dms.sample", method="filterIt")
    *
    * @var string
    */
    public $name;
}

The filterIt method can have any name, but it must take one paramter (the value) and return the filtered value.

Compatibility

This is compatible with Symfony 2.8 and above, including 3.0. For Symfony 2.3+ support use "^2.0".

Contributing

Given you have composer, cloned the project repository and have a terminal open on it:

composer.phar install --prefer-source --dev
vendor/bin/phpunit
vendor/bin/phpcs

The tests should be passing and you are ready to make contributions.

dms-filter-bundle's People

Contributors

cabello avatar dafish avatar dependabot-preview[bot] avatar dependabot[bot] avatar emanueleminotto avatar guilhermeblanco avatar lopsided avatar martin-georgiev avatar msvrtan avatar oldy777 avatar rdohms avatar webonaute avatar yoeunes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

dms-filter-bundle's Issues

v1.1.1 Tag Issue

The v1.1.1 tag has the contents of dms/dms inside the zip, which is causing issues with composer. Could you recreate this zipball?

Just not working?

Hi

I have installed via composer and registered the bundle in AppKernal and have the following

`
namespace AppBundle\Entity;
use DMS\Filter\Rules as Filter;

/**
 * @ORM\Column(type="text")
 * @Assert\NotBlank()
 * @Assert\Length(
 *      min = 250,
 *      minMessage = "Your description must be at least {{ limit }} characters long",
 * )
 * @Filter\StripTags()
 * @Filter\Trim()
 */
private $description;

`

Yet I when I submit the form with something like

xyz

or <script>abc</script> the tags are not stripped.

Have I missed something?

Urls in composer

Hello,

It seems that the url of the repo has been updated, but not in composer.json. This causes failure with composer update.

Service based method not working in symfony 4.4

I am using symfony4.4 with the bundle dms-filter-bundle 4.0
when I call my filter I get any result and any error,
here is my filter from my entity :

    /**
     * @ORM\Column(type="guid")
     * @SfFilter\Service(service="App\Rules\DocumentRules", method="uid")
     */
    protected $uid;

Annotations cache support

Right now every model being filtered process the annotations over and over.
Looking at Service/Filter.php, this exposes exactly the issue by not having a CachedReader usage.
One possible wrapper is FileCacheReader which reuses a similar approach adopted by JMS Serializer and DoctrineBundle.

Simplify dependencies

With Doctrine split into smaller libs, we should pickup only annotations or which ever is needed.

No licence

Would it be possible to add a licence to this bundle please?

Thanks

ObjectWalkers original $object should be available in your custom rule

I found it is impossible to do some advanced filtering with annotations because
i couldn't access any other properties/methods of the object which property is being filtered.

I this case my entity holds language information and i would like to to msisdn phone number filtering.

So it would be great if ObjectWalker would give $object as second parameter to applyFilter or if it would be accessible some another way inside your rule .

Filter: Service

This filter would allow you to pass in a service/method that would be called for filtering. This reduced friction and removed the need to define new Annotation classes for every custom filter.

Special Class Constant Not Available in < PHP55

Hi,

Pulled the V3.1 release of this code and ran into an error on PHP54.

Packagist states that this Requires:
- php: >=5.3.2

However in the class; DMS\Bundle\FilterBundle\Form\Type\FormTypeFilterExtension
Line 78

You are using this syntax:
return FormType::class;

This is only available in >PHP55 versions.

https://secure.php.net/manual/en/language.oop5.constants.php

The special ::class constant are available as of PHP 5.5.0, and allows for fully qualified class name resolution at compile, this is useful for namespaced classes:

Symfony 3.3 error

On upgrade to symfony 3.3 error was ocurred.

PHP Fatal error:  Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: Invalid key "filter" found in arguments of method "__construct()" for service "dms.filter.type_extension": only integer or $named arguments are allowed. in /Dados/open_solutions/web/api-ciand-example/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/ResolveNamedArgumentsPass.php:47

Attach Filters to Fields

As described in #18, validations attached directly to fields are processed against Form (array) data, not the resolved entity, so the filters do not affect the data.

The alternate solution here would be to add the possibility of attaching filters to the fields, so that they would act directly on the form data for non-entity forms. This would be similar to the constraints option.

Some research points to make this viable:

  • does altering the form data ensure the same data is pushed along?
  • how does this play with entity forms, are the effect seen on the final entity?
  • what hook points does symfony provide for this

This is strictly on the Symfony side, so any solutions should be restricted to this bundle, not the underlying library.

property name not found

I got this error:
screenshot from 2014-11-25 08 15 45

property name not found I think this error means property name for category entity but I'm not sure about this error. and I can't search it in google because the error too general to be keyword.

This is happen :

  • only when update (not in create)
  • This is happen when I create new post that has relation to category entity.
  • this form using entity choice for category_id from category entity.

this my type form class:

            ->add('categoryId', 'entity', [
                'class' => $this->parameters['category_entity_name'], // MockizartBlogBundle:MockblogCategory
                'property' => 'name',
                'empty_value' => 'No parent',
                'required' => false
            ])
            ->add('title')

this is notation from category entity:

 /**
     * @Filter\StripTags()
     * @Filter\Trim()
     * @Filter\StripNewlines()
     *
     * @var string
     */
    private $name;

and this is from my post entity class:


    /**
     * Set categoryId
     *
     * @param MockblogCategory $category
     * @internal param int|\Mockizart\Bundle\BlogBundle\Entity\MockblogCategory $categoryId
     * @return MockblogPost
     */
    public function setCategoryId(MockblogCategory $category)
    {
        $this->categoryId = $category;

        return $this;
    }

    /**
     * Get categoryId
     *
     * @return integer 
     */
    public function getCategoryId()
    {
        return $this->categoryId;
    }

my post entity mapping file:

    manyToOne:
        userId:
            targetEntity: Mockizart\Bundle\BlogBundle\Entity\User
            joinColumn:
              name: user_id
              referencedColumnName: id
            type: integer
            nullable: false
            unsigned: false
        categoryId:
            targetEntity: Mockizart\Bundle\BlogBundle\Entity\MockblogCategory
            joinColumn:
              name: category_id
              referencedColumnName: id
            type: integer
            nullable: false
            unsigned: false
            comment: ''

Thanks.

Make standalone

Make this repository standalone, no longer a sub-tree split.
This means adding phpunit config and such.

[2.0.0 Beta 2] Doesn't filter before validation

I'm using the latest beta but the filtering before validation doesn't seem to work.

<?php

namespace AppBundle\Form;

use AppBundle\Form\CustomType;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Iban;

class ProfileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('bank_iban', 'text', array(
            'label' => 'user.profile.label.bank_iban',
            'constraints'               => array(
                new Iban(array(
                    'message' => 'user.account_number.invalid_iban',
                )),
            )
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User',
        ));
    }

    public function getName()
    {
        return 'profile';
    }
}

And my user entity contains this:

/**
 * @var string $bank_iban
 *
 * @Filter\ToUpper
 * @ORM\Column(name="bank_iban", type="string", nullable=true)
 */
private $bank_iban;

When I enter a valid IBAN in lowercase, it complains that the IBAN is not correct. So it doesn't filter before validation. It validates and then applies the filters.

Annotate Service with Attributes

Hello,

I have the following Annotations and Attributes set on an property:

  /**
   * @SfFilter\Service(service="app.utitliy_service", method="removeWhiteSpaces")
   */
   #[Filter\StripTags]
   #[Filter\Trim]
   #[ORM\Column(type: 'string', nullable: true)]
   private ?string $author = null;

I can't neither use this (syntax seems to be correct, but it doesn't work):

   #[SfFilter\Service(options: ["service" => UtilityService::class, "method" => "removeWhiteSpaces"])]

   #[SfFilter\Service(options: ["service" => "app.utitliy_service", "method" => "removeWhiteSpaces"])]

nor use that (for which phpstorm also reclaims syntax error):

   #SfFilter\Service(service: UtilityService::class, method: "removeWhiteSpaces")]

So please what's the correct syntax for using own Filter-methods with attributes? It looks, that Attribute-Syntax doesn't work?!?

Best regards,
Stefan

Symfony 3.0 comptibility

In order to make the bundle compatible with 3.0 we need to break BC for versions below 2.8 of Symfony.

So v2 will remain symfony 2.3+ compatible and the new v3 release will be 2.8 | 3.* compatible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.