Git Product home page Git Product logo

laminas-filter's Introduction

laminas-filter

Build Status Type Coverage

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

The Laminas\Filter component provides a set of commonly needed data filters. It also provides a simple filter chaining mechanism by which multiple filters may be applied to a single datum in a user-defined order.

laminas-filter's People

Contributors

akrabat avatar bakura10 avatar carnage avatar dasprid avatar davidwindell avatar denixport avatar driehle avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar gsteel avatar koopzington avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mwillbanks avatar ocramius avatar prolic avatar ralphschindler avatar renovate[bot] avatar samsonasik avatar sgehrig avatar slamdunk avatar thadafinser avatar thinkscape avatar thomasweidner avatar veewee avatar weierophinney 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

Watchers

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

laminas-filter's Issues

Drop dependency on Laminas\i18n

The depenency on laminas-i18n is problematic because it is cyclic in nature - this makes it infeasible to upgrade SMv4 for a start.

The dependency (in dev) is added so that we can auto-wire filters that are shipped with i18n (Symbols are referenced in src). At the moment, users can install filter without i18n but it makes more sense to me to configure filters present in i18n in that library, not here.

Check for an instance of the `DateTimeInterface` instead of `DateTime` in `DateTimeFormatter`

Bug Report

Q A
Version(s) 2.30.0

Summary

Why are you checking for an instance of the DateTime and not a DateTimeInterface?

if (! is_string($value) && ! is_int($value) && ! $value instanceof DateTime) {

Is there some secret meaning in this?

Current behavior

In my application, there may be a situation when I create a DateTimeImmutable and pass it in a DateTimeFormatter,
expected a formatted string od date/time in return, but get my object back

How to reproduce

$filter = new DateTimeFormatter();

$date = new DateTimeImmutable($inputDate, $inputTimezone);

$start_date = $filter->filter($date->add(new \DateInterval('PT1H')));
$end_date = $filter->filter($date->add(new \DateInterval('PT7H')));

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • Lock file maintenance

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • laminas/laminas-servicemanager ^3.21.0
  • laminas/laminas-stdlib ^3.13.0
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-crypt ^3.11
  • laminas/laminas-i18n ^2.26.0
  • laminas/laminas-uri ^2.11
  • pear/archive_tar ^1.4.14
  • phpunit/phpunit ^10.5.11
  • psalm/plugin-phpunit ^0.19.0
  • psr/http-factory ^1.0.2
  • vimeo/psalm ^5.22.2
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Change the default format to `DATE_ATOM` in `DateTimeFormatter`

Is there any reason why DateTime::ISO8601 is still used in DateTimeFormatter?

Taken from the docs:

DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use DateTime::ATOM or DATE_ATOM for compatibility with ISO-8601 instead.

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)


Originally posted by @geerteltink at zendframework/zend-filter#58

Filter for arithmetic operations

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

I created this filter for an application that converts values from APIs. It's useful for measure unit conversions and making adjustments. For example, an endpoint returns the amount of RAM requested by an user and you can add a security margin.

Improve handling of digits in CamelCaseToSeparator filter

This PR aims to add the behaviour asked in #33

Since the reason behind using the CamelCaseSeparator is tokenizing strings when case is changed, usual expectation is beginning a new token when hitting a number or digit.

I will try to summarize both current and changed behaviour on numbers with some examples:

Original Text Current After this PR
Foo2016Bar  Foo2016-Bar Foo-2016-Bar
March16Events March16-Events  March-16-Events
DigitSuffix42 Digit-Suffix42 Digit-Suffix-42
42metersLong 42metersLong  42-meters-Long

Notice the last example: Beginning of the word with lowercase letter after 42 is also mimics a case-change. I'm still not sure is this a acceptable/desired behaviour or not.

The issue #33 is about the CamelCaseToDashFilter but since it derived from CamelCaseToSeparator like CamelCaseToUnderscore, this change will affect both childs of CamelCaseToSeparator. For this reason, I also added more tests to CamelCaseToDashTest.

After digging dozen of approaches including other platforms such as Java and C# I came up with this final patterns with positive lookbehind and lookaheads. (Achieving same effect with a single regex seems like impossible, at least I give up)

I'm also aware of changing an existing test is not a good practice. Since the expected behaviour is changed for digits, I forced into touching the CamelCaseToUnderscoreTest:

  • Pa2_Title => Pa_2_Title
  • Pa2a_Title => Pa_2a_Title

Altering the CamelCaseToUnderscoreTest seems like mandatory if the desired behaviour will be changed.

All tests are still green.


Originally posted by @edigu at zendframework/zend-filter#45

Undefined index dirname in RenameUpload filter

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: zendframework/zendframework#7274
User: @denchik63
Created On: 2015-02-27T19:21:43Z
Updated At: 2015-11-06T20:46:42Z
Body
Hi everyone.

Form:

/**
 * @return Form
 */
private function getPhotoGalleryForm() {
    $photoGallery = new ObjectFieldset();
    $photoGallery->setObject(new ClientPhotoGallery());
    $photoGallery->setHydrator(new DoctrineOrmHydrator($this->getEntityManager(), 'Admin\Entity\ClientPhotoGallery'));
    $photoGallery->add([
        'name' => 'title',
        'type' => 'AbstractAdmin\Element\ExtendedText',
        'required' => false,
        'options' => array(
            'label' => 'Заголовок',
        ),
    ]);

    $image = new ObjectFieldset();
    $image->setObject(new Image());
    $image->setHydrator(new DoctrineOrmHydrator($this->getEntityManager(), 'Admin\Entity\Image'));
    $image->add([
        'name' => 'id',
        'type' => 'AbstractAdmin\Element\ExtendedHidden',
        'required' => true,
    ]);
    $image->add([
        'name' => 'image',
        'type' => 'AbstractAdmin\Element\ExtendedFile',
        'required' => false,
    ]);

    $images = new ObjectCollection('images', [
        'count' => 16,
        'target_element' => $image,
    ]);

    $photoGallery->add($images);
    $photoGalleries = new ObjectCollection('photoGalleries', [
        'count' => 6,
        'target_element' => $photoGallery,
    ]);

    $data = $this->getDataFieldset();
    $data->setHydrator(new DoctrineOrmHydrator($this->getEntityManager(), 'Admin\Entity\ClientData'));
    $data->add($photoGalleries);

    $form = $this->getSubmitForm('photoGalleryForm', 'photoGallerySubmit');

    $form->add($data);
    $form->setInputFilter($this->getPhotoGalleryInputFilter());

    $form->prepare();

    return $form;
}

InputFilter:

/**
 * @return InputFilter
 */
private function getPhotoGalleryInputFilter() {
    $factory = new Factory();
    $formFilter = new InputFilter();
    $dataFilter = new InputFilter();

    $photoGalleriesFilter = new ApplicationCollectionInputFilter();
    $photoGalleriesFilter->setCount(6);
    $photoGalleryInputFilter = new InputFilter();

    $photoGalleryInputFilter->add($factory->createInput(array(
        'name' => 'id',
        'required' => false,
    )));

    $photoGalleryInputFilter->add($factory->createInput(array(
        'name' => 'title',
        'required' => false,
        'filters' => array(
            array(
                'name' => 'StringTrim',
            ),
            array(
                'name' => 'HtmlEntities',
            ),
        ),
    )));

    $imagesFilter = new ApplicationCollectionInputFilter();
    $imagesFilter->setCount(16);
    $imageInputFilter = new InputFilter();

    $imageInputFilter->add($factory->createInput(array(
        'name' => 'id',
        'required' => false,
    )));

    $imageInputFilter->add($factory->createInput(array(
        'name' => 'image',
        'required' => false,
        'filters' => array(
            array(
                'name' => 'Zend\Filter\File\RenameUpload',
                'options' => array(
                    'target' => '*',
                    'randomize' => true,
                ),
            ),
        ),
        'type' => 'Zend\InputFilter\FileInput',
    )));

    $imagesFilter->setInputFilter($imageInputFilter);

    $photoGalleryInputFilter->add($imagesFilter, 'images');

    $photoGalleriesFilter->setInputFilter($photoGalleryInputFilter);

    $dataFilter->add($photoGalleriesFilter, 'photoGalleries');
    $formFilter->add($dataFilter, 'data');

    return $formFilter;
}

When i tried to save the form i got error - Notice: Undefined index: dirname in Z:\home\findservice\vendor\zendframework\zendframework\library\Zend\Filter\File\RenameUpload.php on line 267

I think it happend because in RenameValidator::getFinalTarget($uploadData) array has empty "tmp_name" element (or elements).


Originally posted by @GeeH at zendframework/zend-filter#30

Drop dependency `Laminas\Uri`

Filter needs to drop laminas-uri in v3.0 because it is no longer maintained.

There is only one filter affected by this change: UriNormalize

Either this filter needs to be deprecated in 2.x and also dropped in 3.x or the filter needs to be re-implemented to work without laminas-uri.

Comments/suggestions are welcomed with regard to this choice - it's much less work to simply drop the filter.

From what I can tell, the filter is mostly concerned with setting the scheme for schemaless URIs, or enforcing the scheme for any valid URI given - it is possible that re-implementing with built-in PHP functions such as parse_url will be sufficient replacement.

[RFC]: Removal of `UriNormalizer`

RFC

Q A
Proposed Version(s) 3.0.0
BC Break? Yes

Goal

Removal of the UriNormalize filter.

Background

laminas/laminas-uri is marked as security only and will most probably not receive any more updates.
That package does also require laminas/laminas-validator, most probably to validate some stuff (haven't had a look).
I was trying to add support for laminas/laminas-servicemanager v4 in here and realized that there laminas-uri does require the service manager as well (maybe due to transitive dependency to the validator component.

To reduce the complexity of this component and to remove another component which will most probably die at some point in favor of diactoros, which does also provide URI stuff while respecting PSR-7, I think we should remove the filter from here.

Considerations

UriNormalization won't be possible with v3 anymore.

Proposal(s)

Was thinking about replacing it with diactoros but the URI component does a whole lotta normalization stuff and therefore, this that filter is totally dependent on internal laminas-uri logic.
IMHO, the filter should get removed and/or re-implemented in one of the upcoming v3 minors while using diactoros.
The normalization logic should be part of this library, could be migrated from laminas-uri for example.
I tried that for a moment but ended up requiring laminas/laminas-escaper as well which made me stop trying.

Appendix

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (local>laminas/.github:renovate-config)

ToString filter missing?

Feature Request

Laminas-filter component has ToFloat, ToInt and ToNull filters but ToString is missing.

Q A
New Feature yes
RFC no
BC Break no

Summary

This filter should be similar as ToInt:

class ToString extends AbstractFilter
{
    public function filter($value)
    {
        if (
            is_scalar($value)
            || $value === null
            || $value instanceof Stringable
        ) {
            return (string)  $value;
        }

        return $value;
    }
}

Your opinions?

Declaration of Laminas\Filter\FilterPluginManager::get($name, ?array $options = NULL) must be compatible with Laminas\ServiceManager\AbstractPluginManager::get($name, $options = Array, $usePeeringServiceManagers = true)

Bug Report

Q A
Version(s) 2.15.0

Summary

Fatal error: Declaration of Laminas\Filter\FilterPluginManager::get($name, ?array $options = NULL) must be compatible with Laminas\ServiceManager\AbstractPluginManager::get($name, $options = Array, $usePeeringServiceManagers = true) in /app/vendor/laminas/laminas-filter/src/FilterPluginManager.php on line 521

Current behavior

Compilation Failed

How to reproduce

Version of laminas/laminas-filter (2.15.0)
Version of laminas/laminas-servicemanager (2.7.11)

Expected behavior

No error

Mark filters as attributes

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Adding the #[Attribute] tag to filters would allow several new use cases for the library.

For example, object validation (i.e., a DTO):

use Laminas\Filter;

final class CreateNewBookDto extends Dto
{
    #[Filter\StringTrim]
    public $author;

    #[Filter\StringTrim]
    #[Filter\StringToUpper]
    public $title;

    public function __construct($author, $title)
    {
         $this->author = $author;
         $this->title = $title;
    }
}

In this case, filters could be read using reflection to create an automated pipeline to filter object properties.

Other cases could include route filtering of HTTP requests, console input filtering, etc.

Hydration of object attached to form with unfiltered values on submission

BC Break Report

Q A
Version 2.13.0

Summary

After updating to the recent version of laminas, when submitting a form, the object set to be hydrated by the form submission does not get the filtered values from the inputs, it gets raw data.

Previous behavior

If I understand correctly, when submitting the form in previous version of laminas, the method Laminas\InputFilter\Input->isValid() assigned the filtered value to the form input which subsequently moved to the corresponding property of the hydrated object.

Current behavior

The form's object gets hydrated with the raw values from the form, not filtered

How to reproduce

Just check the resulting object after hydration.

`Boolean` filter should also accept `int-mask<self::CONSTANTS>` via `__construct`

Bug Report

Q A
Version(s) 2.26.0

Summary

The Boolean filter (and maybe others, did not finished my recent composer update psalm check-ups) should also accept int-mask-of<self::CONSTANTS> (as it does in its psalm-type Options).

Current behavior

Argument 1 of Laminas\Filter\Boolean::__construct expects "all"|"array"|"boolean"|"false"|"float"|"integer"|"localized"|"null"|"php"|"string"|"zero"|1|2|4|8|16|32|64|127|128|256|511|array<"casting"|"translations"|"type"|int, 0|32|64|96|128|160|192|224|256|288|320|352|384|416|448|480|array<array-key, mixed>|bool|positive-int>|iterable<mixed, mixed>|null, but 129 provided (see https://psalm.dev/004)
        $filter = new Boolean(Boolean::TYPE_BOOLEAN | Boolean::TYPE_FALSE_STRING, false);

How to reproduce

$filter = new Boolean(Boolean::TYPE_BOOLEAN | Boolean::TYPE_FALSE_STRING);

Run psalm over this example.

Expected behavior

No psalm error as the constructor argument is valid.

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a .psalm.xml.dist in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Cannot use object of type Closure as array

Bug Report

When attempting to instantiate Laminas Filter I'm getting an error about the Closure as array.

Q A
Laminas Filter Version(s) 2.9.3

Current behavior

Getting the following error:

In AddonLoader.php line 29:                     
Cannot use object of type Closure as array  

How to reproduce

Added laminas filter to my laravel project using composer.

Added use Laminas\Filter\StripTags; to my controller.

I then applied the following code to my method:

$allowedElements = [
       'allowTags' => [
               'ul','li','ol','br','p','b','strong','i','em','h1','h2','h3','h4','h5','a'
       ],
        'allowAttribs' => [
               'href'
      ]
];
$filter = new StripTags($allowedElements);
$htmltext = $filter->filter($htmltext);

Expected behavior

Should result in a string for $htmltext.

DateTimeFormatter: Add option to return invalid date string unfiltered

  • add documentation for DateTimeFormatter. Addresses #58.
  • add @todo notation in docblock for $format property
  • add tests for new option
  • Are you fixing a bug?
    • Detail how the bug is invoked currently.
$filter = new DateTimeFormatter();
$filter->filter('2013-31-31'); // throws exception
  • Detail the original, incorrect behavior.
    DateTimeFormatter::filter throws an exception in the event that the input is not a parsable date string
  • Detail the new, expected behavior.
$filter = new DateTimeFormatter();
$filter->setThrowInvalidDateException(false);
$filter->filter('2013-31-31'); // returns "2013-31-31"
  • Base your feature on the master branch, and submit against that branch.
  • Add a regression test that demonstrates the bug, and proves the fix.
  • Add a CHANGELOG.md entry for the fix.

Originally posted by @marcguyer at zendframework/zend-filter#84

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Problem with FileInput

My upload file validator is configured as below:

[ 'type' => FileInput::class, 'name' => 'image_2', 'required' => false, 'validators' => [ [ 'name' => 'FileUploadFile', ], [ 'name' => 'FileMimeType', 'options' => [ 'mimeType' => [ 'image/jpeg', 'image/png' ] ] ], [ 'name' => 'FileIsImage' ], [ 'name' => 'FileImageSize', 'options' => [ 'minWidth' => 128, 'minHeight' => 128, 'maxWidth' => 4096, 'maxHeight' => 4096 ] ], ], 'filters' => [ [ 'name' => 'FileRenameUpload', 'options' => [ 'target' => './public/img', 'useUploadName' => false, 'useUploadExtension' => true, 'overwrite' => true, 'randomize' => true, ] ] ], ],
The method isValid() is not called from the class FileInput::class , but from the class Input::class , even though I indicated type as FileInput::class.

I checked this situation very carefully and I really believe that this behavior is not appropriate.

I would like to help if doing something wrong.

[RFC]: Deprecate Compression Adapters Lzf, Rar and Snappy

RFC

Q A
Proposed Version(s) 2.x.
BC Break? Not yet

Further to #78

Rar, Lzf and Snappy all need extra work to get their respective custom extensions installed.

Propose to deprecate these adapters in a forthcoming minor release of the 2.x series for removal in 3.0 in order to reduce maintenance burden of probably infrequently used adapters.

PSR-7 file upload parameter naming consistency.

  • Is this related to quality assurance?
  • Is this related to documentation?
    Upgrading my setup to released version of #70 caused some confusion. Updating parameter to help resolve it, and suggest a documentation edit to explain where the instances could come from, as I couldn't figure it out without looking at the diff changes of previous PR refactorings.

Add missing unit tests for new options.


Originally posted by @alextech at zendframework/zend-filter#82

Zend\Filter\File\RenameUpload behaves differently when folder exists and not

code example:

$filter = new \Zend\Filter\File\RenameUpload([
    'target' => './public/img/logotypes/logo',
    'use_upload_extension' => true,
    'randomize' => true,
]);
$file = $filter->filter($file_data);
echo $file['tmp_name'];

when logo folder exists returned value would be:

./public/img/logotypes/logo/phpj7GsVi_55f03311ed828.jpg

when logo folder doesn't exists returned value would be:

./public/img/logotypes/logo_55f034e642bf3.jpg

I can't beleave this is desired behavior because this can lead to bugs.
Guess I used this incorrectly because I wanted logo prefix this worked for me until someone created logo folder then everything gone bad :(


Originally posted by @svycka at zendframework/zend-filter#4

PHP 8.1 support

I was wondering if PHP 8.1 support is planned for laminas-filter. At the moment I'm getting a lot of deprecated warnings:

PHP Deprecated:  Return type of Laminas\InputFilter\BaseInputFilter::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in vendor\laminas\laminas-inputfilter\src\BaseInputFilter.php on line 70
PHP Deprecated:  Return type of Laminas\Filter\FilterChain::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in vendor\laminas\laminas-filter\src\FilterChain.php on line 92

Remove Deprecated Compression Adapters

Q A
BC Break yes

Summary

lzf, snappy and rar compression adapters are deprecated and require removal in 3.0

  • Remove Adapters & Tests
  • Remove pre-install.sh
  • Update documentation

Warn on actual alterations

Our project is using Zend filters for security purposes. For example, we might want to ensure that a text input contains an integer using Zend\Filter\ToInt. filter() gives us the guarantee that the returned value is an integer. Unfortunately, it may quietly alter the input.

If the input is string "3" and the output is int 3, there is no problem.
But if the input is string "four" and the output is 0, there is a problem - either the wrong filter was used, or the UI should not have let "four" be entered.

To ensure that problems are detected, filter() should warn when an actual alteration is done, for example by triggering a PHP warning.


Originally posted by @Chealer at zendframework/zend-filter#63

Test failure with OpenSSL 3.0

Probably related to old deprecated algo

There were 5 errors:
1) LaminasTest\Filter\Encrypt\BlockCipherTest::testGetSetEncryption
Laminas\Filter\Exception\InvalidArgumentException: The algorithm 'blowfish' is not supported
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt/BlockCipher.php:124
/builddir/build/BUILD/laminas-filter-0fc5dcd27dc22dba1a2544123684c67768fc5f88/test/Encrypt/BlockCipherTest.php:88
2) LaminasTest\Filter\Encrypt\OpensslTest::testBasicOpenssl
Laminas\Filter\Exception\RuntimeException: Openssl was not able to encrypt your content with the given options
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt/Openssl.php:366
/builddir/build/BUILD/laminas-filter-0fc5dcd27dc22dba1a2544123684c67768fc5f88/test/Encrypt/OpensslTest.php:58
3) LaminasTest\Filter\Encrypt\OpensslTest::testEncryptionWithDecryptionWithPackagedKeys
Laminas\Filter\Exception\RuntimeException: Openssl was not able to encrypt your content with the given options
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt/Openssl.php:366
/builddir/build/BUILD/laminas-filter-0fc5dcd27dc22dba1a2544123684c67768fc5f88/test/Encrypt/OpensslTest.php:244
4) LaminasTest\Filter\Encrypt\OpensslTest::testEncryptionWithDecryptionAndCompressionWithPackagedKeys
Laminas\Filter\Exception\RuntimeException: Openssl was not able to encrypt your content with the given options
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt/Openssl.php:366
/builddir/build/BUILD/laminas-filter-0fc5dcd27dc22dba1a2544123684c67768fc5f88/test/Encrypt/OpensslTest.php:268
5) LaminasTest\Filter\EncryptTest::testBasicOpenssl
Laminas\Filter\Exception\RuntimeException: Openssl was not able to encrypt your content with the given options
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt/Openssl.php:366
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/Encrypt.php:159
/builddir/build/BUILDROOT/php-laminas-filter-2.12.0-1.fc36.noarch/usr/share/php/Laminas/Filter/AbstractFilter.php:82
/builddir/build/BUILD/laminas-filter-0fc5dcd27dc22dba1a2544123684c67768fc5f88/test/EncryptTest.php:101
ERRORS!
Tests: 975, Assertions: 1848, Errors: 5, Skipped: 16, Incomplete: 6.

Bugfix Version jump probably has a BC (from 2.7.1 to 2.7.2)

Hi Zend-Filter Team,

unfortunately the last bugfix update seems to contain a BC.

This is the diff i am talking about.
zendframework/zend-filter@76a6967#diff-d178b1651bd6efe807b184425f956970

The commit message actually just says "Ensure tests run against all PHP versions" but in fact in the file src/Encrypt/BlockCipher.php in line 66 and then 68 there is a breaking change.

Background:

  • we are using Zend-Crypt v3.1.0 already for quite a while.
  • we are using Zend-Filter as well (lastest before the update in v2.7.1)
  • we are using mcrypt to encrypt strings (with rijndael-128 as the algorithm)

The Problem:

  • with the v2.7.2 (bugfix version) the $cipherType was changed from hardcoded mcrypt to a value that is fetched from the SymmetricPluginManager in the file mentioned above
  • i am talking about those lines
$cipherPluginManager = CryptBlockCipher::getSymmetricPluginManager();
$cipherType = $cipherPluginManager->has('openssl') ? 'openssl' : 'mcrypt';
  • the problem is that $cipherPluginManager->has('openssl') will always return true if you use Zend-Crypt > v3
  • the real problem derives from that because there is no setting to tell the SymmetricPluginManager or the BlockChiper class which cipherType to use but it is implicitly set

The Result:

  • as a result whenever the Crypt class is loaded with the algorithm we use (rijndael-128) it will fail because the openssl implementation does not contain this algo in the $encryptionAlgosproperty
  • it fails because this particular algo can only be found in the mcrypt class

Possible Solution:

  • have a possibility to let the user decide which cipherType to use
  • the default might still be set to openssl but it would be really helpful to have the possibility to override that, e.g. from within the global config

Thats my report for now. Shall i create a PullRequest for a potential change including setting the desired cipherType from the config?

Thanks in advance.


Originally posted by @null9beta at zendframework/zend-filter#57

CamelCaseToDashFilter & numbers

Not sure if this is expected behavior but seems like a bug to me, but if you pass a string with numbers into CamelCaseToDashFilter the dash is not applied before a number, please see below for a failing unit test.

    public function testFilterSeparatesCamelCasedWordsContainingNumbersWithDashes()
    {
        $string   = 'ItIs2016';
        $filter   = new CamelCaseToDashFilter();
        $filtered = $filter($string);
        $this->assertNotEquals($string, $filtered);
        $this->assertEquals('It-Is-2016', $filtered);
    }

Originally posted by @joshhornby at zendframework/zend-filter#33

Remove Deprecated Encryption & Decryption Filters

Q A
BC Break yes

Summary

The Encrypt and Decrypt filters are deprecated for removal in 3.0

  • Remove Filters and relevant tests
  • Remove Relevant Adapters, Adapter Interface and tests (i.e. BlockCipher and OpenSSL)

Non-string scalar types produce a fatal error with StripNewlines

Bug Report

Q A
Version(s) 2.13.0

Summary

On PHP 7.4, str_replace would accept any scalar value and implicitly cast it to a string (even with declare(strict_types=1)). As of PHP 8.0, anything but string|array to the 3rd argument of str_replace throws a fatal error.

See: https://3v4l.org/YOktG

With the PHP 8.1 release, declare(strict_types=1) was added to all files (presumably due to the coding standard) meaning that previously valid values passed to StripNewLines are now throwing a fatal error.

Current behavior

StripNewLines::filter(123) throws a fatal error on the latest version whereas previously, it would be implicitly cast to a string.

How to reproduce

I intend to submit a PR to introduce failing tests along with a fix.

Expected behavior

Previously working values should not throw a fatal error.

RenameUpload filter breaks UploadFile validator

Bug Report

Q A
Version laminas-validator 2.15.0
Version laminas-filter 2.12.0

Summary

when the RenameUpload filter is added to a field containing the UploadFile validator the UploadFile validator fails and issues an error about a possible attack

the reason for that is that inside the UploadFile a check is performed using the tmp_name to check if the file was uploaded by using the method is_uploaded_file. as the RenameUpload filter is applied before calling the validator the tmp_name has been already changed based on the configuration for the RenameUpload filter and so the check fails as tmp_name is no longer the name to the uploaded file in the $_FILES array

Current behavior

impossible to upload a file when the RenameUpload filter and the UploadFile validator are used on the same field

How to reproduce

configure a field like this (using array notation for configuring a field):

    public function getInputFilterSpecification(): array
    {
        return [
            'logo' => [
                'required' => false,
                'validators' => [
                    [
                        'name' => UploadFile::class,
                    ],
                ],
                'filters' => [
                    [
                        'name' => RenameUpload::class,
                        'options' => [
                            'target' => './public_html/img/uploads/logo',
                            'randomize' => true,
                        ],
                    ],
                ],
            ],
        ];
    }

Expected behavior

the filter and validator can be used together

References to Zend Version 2.3.8p2

Bug Report

Hi Laminas-Filter team,

unfortunately References to Zend (instead of Laminas) can be found in Version 2.3.8p2 (unlike for example laminas-view 2.3.8p2)

Q A
Version(s) 2.3.8, 2.3.8p1, 2.3.8p2

Summary

I am in the process of migrating a project from Zend to Laminas via laminas-migration migrate script. Due to dependency issues I can not yet upgrade to a newer version beyond 2.3.8(p2). Even though the laminas-dependency-plugin and the laminas-zendframework-bridge are installed I am getting errors due to multiple declarations of classes in the same namespace.

Current behavior

Namespaces and use statements reference Zend instead of Laminas

Expected behavior

Namespaces and use statements reference Laminas instead of Zend

I do have a fork where I ran the laminas-migration migrate script, fixed missing dependencies, renamed Zend_Filter and ZendTest, and fixed the PHPUnit tests. If there was a target branch available I would create a pull request.

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.