Code Monkey home page Code Monkey logo

laminas-cache-storage-adapter-filesystem's Introduction

laminas-cache-storage-adapter-filesystem

Build Status type-coverage Psalm level

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

Мы, участники 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!"

This library provides …

Installation

Run the following to install this library:

$ composer require laminas/laminas-cache-storage-adapter-filesystem

Documentation

Browse the documentation online at https://docs.laminas.dev/laminas-cache-storage-adapter-filesystem/

Support

laminas-cache-storage-adapter-filesystem's People

Contributors

akrabat avatar binarykitten avatar boesing avatar brettmc avatar dependabot[bot] avatar fezfez avatar ghostwriter avatar gsteel avatar kokspflanze avatar koopzington avatar laminas-bot avatar maks3w avatar marc-mabe avatar michalbundyra avatar micheh avatar ocramius avatar odan avatar peterprototypes avatar phpgangsta avatar prolic avatar renovate[bot] avatar samsonasik avatar skors avatar slamdunk avatar tdutrion avatar thomasvargiu avatar tysonandre avatar umpirsky avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

laminas-cache-storage-adapter-filesystem's Issues

Cache type not usable if global sys_tmp_dir not writeable

BC Break Report

Q A
Version 2.3.x-dev

Summary

When you define an own cache_dir, the system always tries the default sys_get_temp_dir first, even though you are not using it. If anything is wrong with it (like no write access), you cannot create a FileSystem Adapter at all.

Previous behavior

The sys_get_temp_dir() was only used in case that no other dir was defined.

Current behavior

I've provided the following config for the filesystem:

'name'    => 'filesystem',
'adapter' => 'filesystem',
'options' => [
    'cache_dir' => 'data/cache/',
    'ttl'       => '3600'
],
'plugins' => [
    [
        'name'    => 'exception_handler',
        'options' => [
            'throw_exceptions' => true,
        ],
    ],
    [
        'name' => 'Serializer'
    ]
]

As you can see, the cache_dir is provided in the settings.
However, since the new version, the FileSystemOptions always calls the setCacheDir with the parameter null:
$this->setCacheDir(null); (FileSystemOptions.php:115)

This results in a fallback to sys_get_temp_dir(), which will then be checked and - on my test maschine - was not writable. The Adapter throws and cannot be created then, though right after that, it would overwrite the CacheDir with the correct and working path.

How to reproduce

Define your sys_temp_dir in your php.ini to a non-existing or not-writable path.
Then try to create an adapter with a valid cache_dir configuration.
It will not work and fails with one exception of the method normalizeCacheDirectory

Investigation of total space "cache" clearance when `cache_dir` option changes

I must admit, that I am not even aware of the functionality of this code. We are detaching a listener from the event handler, which is always null.
So there is absolutely no chance that this code has any impact.

I wonder if this could be removed.

When looking into the previous implementation, this was related to the Filesystem#getTotalSpace method and was to reset an already detected, cached, total space value for a preconfigured directory. Not sure if the detach logic provides anything useful - but this is just for the sake of completeness here. I will create an issue from this comment for further investigation and refactoring.

Originally posted by @boesing in #26 (review)

PHP 8.3 support

Feature Request

Q A
New Feature yes
RFC yes/no
BC Break yes/no

Summary

Make this laminas/cache Adapter compatible with new php 8.3 release.

Compatibility with PSR-16/PSR-6

Feature Request

Summary

PSR-16 allows "A-Z, a-z, 0-9, , and ." as valid key characters for the cache item name. But the key name pattern of the Filesystem storage is "/^[a-z0-9+-]*$/Di" and therefore doesn't match PSR-16 since "." isn't allowed here. This leads to errors when using the simple cache decorator on libraries such as "browscap/browscap-php" that has a cache item named "browscap.version".

Current behavior

Using the simple cache decorator with a laminas cache storage such as Filesystem throws an Exception when a dot is used inside the cache item name.

Expected behavior

The cache storage should accept key names with a dot since it's specified by PSR-16 and breaks standard compatibility with the simple cache decorator. A valid key pattern for the Filesystem storage could be this one "^[a-z0-9_+-.]*$/Di".

Metadata is missing `filesize`

Bug Report

Q A
Version(s) since 1.0.0 until 2.3.x

Summary

The metadata is missing filesize even tho it is both documented via constant and adapter documentation.

Current behavior

The metadata provided does not contain filesize.

How to reproduce

Call Filesystem#getMetadata with any key and check return value.

Expected behavior

Filesystem#getMetadata does return the filesize metadata.

Documenting adapter options

To document the adapter options, I have tried to extract the properties of the option class via script.

Here is a first result:

Option Name Description Type Default Value
cache_dir Directory to store cache files string The cache directory null
clear_stat_cache Call clearstatcache enabled? bool true
dir_level How much sub-directaries should be created? int 1
dir_permission Permission creating new directories false|int 0700
file_locking Lock files on writing bool true
file_permission Permission creating new files false|int 0600
key_pattern Overwrite default key pattern string /^[a-z0-9_\+\-]*$/Di
namespace_separator Namespace separator string -
no_atime Don't get 'fileatime' as 'atime' on metadata bool true
no_ctime Don't get 'filectime' as 'ctime' on metadata bool true
umask Umask to create files and directories false|int false
suffix Suffix for cache files string dat
tag_suffix Suffix for tag files string tag

/**
* Directory to store cache files
*
* @var string|null The cache directory
*/
private ?string $cacheDir = null;
/**
* Call clearstatcache enabled?
*/
private bool $clearStatCache = true;
/**
* How much sub-directaries should be created?
*/
private int $dirLevel = 1;
/**
* Permission creating new directories
*
* @var false|int
*/
private $dirPermission = 0700;
/**
* Lock files on writing
*/
private bool $fileLocking = true;
/**
* Permission creating new files
*
* @var false|int
*/
private $filePermission = 0600;
/**
* Overwrite default key pattern
*
* @var string
*/
protected $keyPattern = self::KEY_PATTERN;
/**
* Namespace separator
*/
private string $namespaceSeparator = '-';
/**
* Don't get 'fileatime' as 'atime' on metadata
*/
private bool $noAtime = true;
/**
* Don't get 'filectime' as 'ctime' on metadata
*/
private bool $noCtime = true;
/**
* Umask to create files and directories
*
* @var false|int
*/
private $umask = false;
/**
* Suffix for cache files
*/
private string $suffix = 'dat';
/**
* Suffix for tag files
*/
private string $tagSuffix = 'tag';

@boesing
The DocBlocks might need to be extended, but would this be a viable solution? Would all options then be included?

Dependency Dashboard

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

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

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-cache ^3.10.0
  • laminas/laminas-cache-storage-adapter-benchmark ^1.1.0
  • laminas/laminas-cache-storage-adapter-test ^2.0 || 2.0.x-dev
  • laminas/laminas-coding-standard ~2.4
  • laminas/laminas-serializer ^2.14.0
  • phpunit/phpunit ^9.5.26
  • psalm/plugin-phpunit ^0.19.0
  • vimeo/psalm ^5.18
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/release-on-milestone-closed.yml

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

Not working with laminas/laminas-eventmanager:3.4

Hello,

I've update to ^2.0 but a got an issue

aminas\EventManager\EventManager::detach(): Argument #1 ($listener) must be of type callable, null given, called in /var/www/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php on line 115

The $listerne var is null instead of being a callable, see :

(

// clean total space buffer on change cache_dir
$events = $this->getEventManager();
$handle = null;
$totalSpace = &$this->totalSpace;
$callback = function ($event) use (&$events, &$handle, &$totalSpace) {
$params = $event->getParams();
if (isset($params['cache_dir'])) {
$totalSpace = null;
$events->detach($handle);
}
};
)

EventManagerInterface :

https://github.com/laminas/laminas-eventmanager/blob/9e11e32de9eb66451ddaba81d282cccb9bbf245f/src/EventManagerInterface.php#L96-L106

PHP 8.3 Support required...

Feature Request

Q A
New Feature yes

Summary

@boesing when will PHP 8.3 support be available in this package?

Actually the most packages uses the filesystem Adapter. This is the reason why the most applications are have a hard dependency to this package.

This results into a high prio for this package... Or I am wrong...

Br
Nusphere

Filesystem adapter does not require `laminas-cache` in v3

Bug Report

Q A
Version(s) v2+

Summary

Since v2 release, this adapter does not require laminas-cache.

Current behavior

No real behavior as I don't think that this component is required directly.

How to reproduce

Require this component, static analyzers will directly rage due to missing laminas-cache dependency.

Expected behavior

laminas/laminas-cache is installed as well.

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.

PHP 8.1: Adapter is incompatible with `IteratorAggregate::getIterator`

Bug Report

Q A
Version(s) latest

Summary

PHP Fatal error:  During inheritance of IteratorAggregate: Uncaught Return type of Adapter::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

Current behavior

Tests are failing.

How to reproduce

Execute tests with PHP 8.1

Expected behavior

Tests are passing.

Add a file_user and file_group option to Filesystem Adapter

Feature Request

Q A
New Feature yes
RFC yes
BC Break no

Summary

I use Laminas\Cache\Storage\Adapter\FileSystem. It creates/accesses cache files from webserver requests (Apache) and from cron jobs. These run under different users which are not in the same group. That leads to an error when writing a file created by the other.
I think it would be nice to be able to specify as which user/group (chown) the cache files should be created.
Can I submit a PR to add this option? Or am I approaching this the wrong way?

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 `unlink()` and `chmod()` on nonexistent files

Hi! I have such errors:

[04-Jan-2021 21:27:02 Europe/Warsaw] PHP Warning:  unlink(/home/users/default/public_html/PRIVATE/data/cache/laminascache-5a/laminascache--d751713988987e9331980363e24189ce.tag): No such file or directory in /home/users/default/public_html/PRIVATE/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php on line 412
[05-Jan-2021 13:01:22 Europe/Warsaw] PHP Fatal error:  Uncaught ErrorException: chmod(): No such file or directory in /home/users/default/public_html/PRIVATE/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php:1638
Stack trace:
#0 [internal function]: Laminas\Stdlib\ErrorHandler::addError(2, 'chmod(): No suc...', '/home/users/def...', 1638, Array)
#1 /home/users/default/public_html/PRIVATE/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php(1638): chmod('/home/users/def...', 384)
#2 /home/users/default/public_html/PRIVATE/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php(337): Laminas\Cache\Storage\Adapter\Filesystem->putFileContent('/home/users/def...', 'PicturesTS\nPict...')
#3 /home/users/default/public_html/PRIVATE/module/CoreTS/src/Model/TsCache.php(0): Laminas\Cache\Storage\Adapter\Filesystem->setTags('PicturesTS_Pict...', Array)
#4 /home/users/default/public_html/PRIVATE/module/CoreTS/src/Model/TsBaseModel.php(0): CoreTS\Model\TsCache->saveCache(Object(Propel\Runtime in /home/users/default/public_html/PRIVATE/vendor/laminas/laminas-cache-storage-adapter-filesystem/src/Filesystem.php on line 1641

Probably caused by too fast / multiple cache cleaning.

Does this code:

...should look like this:

if (file_exists($pathname)) {
    unlink($pathname);
}

To prevent code errors like this?

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.