PHP code example of responsive-sk / slim4-paths

1. Go to this page and download the library: Download responsive-sk/slim4-paths library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

responsive-sk / slim4-paths example snippets


use ResponsiveSk\Slim4Paths\Paths;

$paths = Paths::withPreset('laravel', __DIR__);

// Laravel-specific paths
echo $paths->get('app');           // /path/to/app
echo $paths->get('controllers');   // /path/to/app/Http/Controllers
echo $paths->get('models');        // /path/to/app/Models
echo $paths->get('views');         // /path/to/resources/views
echo $paths->get('storage');       // /path/to/storage
echo $paths->get('migrations');    // /path/to/database/migrations
echo $paths->get('uploads');       // /path/to/storage/app/public

$paths = Paths::withPreset('slim4', __DIR__);

// Slim 4-specific paths
echo $paths->get('src');           // /path/to/src
echo $paths->get('handlers');      // /path/to/src/Handler
echo $paths->get('actions');       // /path/to/src/Action
echo $paths->get('templates');     // /path/to/templates
echo $paths->get('cache');         // /path/to/var/cache
echo $paths->get('logs');          // /path/to/var/log
echo $paths->get('uploads');       // /path/to/var/uploads

$paths = Paths::withPreset('mezzio', __DIR__);
// or
$paths = Paths::withPreset('laminas', __DIR__);

// Mezzio-specific paths
echo $paths->get('src');           // /path/to/src
echo $paths->get('handlers');      // /path/to/src/Handler
echo $paths->get('modules');       // /path/to/modules
echo $paths->get('data');          // /path/to/data
echo $paths->get('content');       // /path/to/content
echo $paths->get('database');      // /path/to/data/database

// Get all available presets
$presets = Paths::getAvailablePresets();
// ['laravel', 'slim4', 'mezzio', 'laminas']

// Get preset information
$info = Paths::getPresetInfo();
foreach ($info as $key => $preset) {
    echo "{$key}: {$preset['name']} - {$preset['description']}\n";
}

use ResponsiveSk\Slim4Paths\Paths;

// Initialize with base path and configuration
$paths = new Paths('/path/to/project', [
    'templates' => '/path/to/project/templates',
    'content' => '/path/to/project/content',
    // ... more paths
]);

// Basic path access
$templatePath = $paths->templates();
$configPath = $paths->config();
$publicPath = $paths->public();

use ResponsiveSk\Slim4Paths\Paths;

// From a file at src/Modules/Core/SomeClass.php, go up 3 levels to project root
$paths = Paths::fromHere(__DIR__, 3);

// From a file at src/Services/SomeService.php, go up 2 levels to project root
$paths = Paths::fromHere(__DIR__, 2);

// Use resolved paths
$dbPath = $paths->storage('database.db');
$logPath = $paths->logs('app.log');

// Set environment variable
putenv('APP_BASE_PATH=/path/to/project');

// Create Paths instance from environment
$paths = Paths::fromEnv();

// Or use custom environment variable
putenv('BASE_PATH=/custom/path');
$paths = Paths::fromEnv('BASE_PATH');

// Environment-based initialization
$paths = Paths::fromEnv(); // or Paths::fromHere(__DIR__, 3)

// Use existing path methods
$paths->base();                    // Project root: /path/to/project
$paths->public();                  // Public directory: /path/to/project/public
$paths->config();                  // Config directory: /path/to/project/config
$paths->src();                     // Source directory: /path/to/project/src

// Configured paths work as expected
$paths->storage('database.db');    // /path/to/project/var/storage/database.db
$paths->logs('app.log');           // /path/to/project/var/logs/app.log

$paths->base()          // Project root directory
$paths->config()        // Configuration directory
$paths->src()           // Source code directory
$paths->public()        // Public web directory
$paths->var()           // Variable/runtime directory
$paths->vendor()        // Vendor directory

$paths->templates()                    // Main templates directory
$paths->views()                        // Views directory
$paths->layouts('main.php')            // Layout templates
$paths->partials('header.php')         // Partial templates

$paths->content()                      // Content root directory
$paths->articles('post.md')            // Article files
$paths->orbit()                        // Orbit database directory
$paths->orbitDatabase('app')           // Orbit database file (app.db)

$paths->moduleConfig('Core/Storage')           // Module config file
$paths->moduleRoutes('Core/Template')          // Module routes file
$paths->moduleTemplates('Optional/Blog')       // Module templates directory

$paths->css('app.css')             // CSS files
$paths->js('main.js')              // JavaScript files
$paths->images('logo.png')         // Image files
$paths->fonts('roboto.woff2')      // Font files
$paths->media('video.mp4')         // Media files

$paths->docs('api.md')             // Documentation files
$paths->scripts('deploy.sh')       // Script files
$paths->bin('console')             // Executable files
$paths->tests('UserTest.php')      // Test files

$paths->keys('private.key')        // Security keys
$paths->exports('data.json')       // Export files
$paths->imports('import.csv')      // Import files
$paths->logs('app.log')            // Log files
$paths->cache('views')             // Cache files
$paths->storage('uploads')         // Storage files

$paths->lang('en', 'messages.php')     // Language files
$paths->translations('app.po')          // Translation files
$paths->locales()                       // Locales directory

// Secure path joining
$safePath = $paths->getPath($baseDir, $relativePath);

// Automatic validation
try {
    $maliciousPath = $paths->getPath('/safe/dir', '../../../etc/passwd');
} catch (InvalidArgumentException $e) {
    // Path traversal detected and blocked
    echo $e->getMessage(); // "Path traversal detected in: ../../../etc/passwd"
}

$config = [
    'base_path' => '/path/to/project',
    'paths' => [
        'templates' => '/path/to/project/templates',
        'content' => '/path/to/project/content',
        'public' => '/path/to/project/public',
        // ... more paths
    ]
];

$paths = new Paths($config['base_path'], $config['paths']);

use ResponsiveSk\Slim4Paths\Paths;
use Slim\Factory\AppFactory;

$app = AppFactory::create();

// Add Paths to container
$container = $app->getContainer();
$container->set(Paths::class, function() {
    $config =  $paths->templates($args['name'] . '.php');
    
    if (!file_exists($templatePath)) {
        throw new \Slim\Exception\HttpNotFoundException($request);
    }
    
    // Render template...
});

// Article management
$articlePath = $paths->articles('getting-started.md');
$articlesDir = $paths->articles();

// Database management
$appDb = $paths->orbitDatabase('app');      // var/orbit/app.db
$markDb = $paths->orbitDatabase('mark');    // var/orbit/mark.db
$cacheDb = $paths->orbitDatabase('cache');  // var/orbit/cache.db

// Content organization
$contentRoot = $paths->content();           // content/
$docsContent = $paths->content('docs');     // content/docs/

// Module configuration
$storageConfig = $paths->moduleConfig('Core/Storage');
// Result: src/Modules/Core/Storage/config.php

// Module routes
$templateRoutes = $paths->moduleRoutes('Core/Template');
// Result: src/Modules/Core/Template/routes.php

// Module templates
$blogTemplates = $paths->moduleTemplates('Optional/Blog');
// Result: src/Modules/Optional/Blog/templates/

$blogArticleTemplate = $paths->moduleTemplates('Optional/Blog', 'article.php');
// Result: src/Modules/Optional/Blog/templates/article.php

// Good - secure path joining
$filePath = $paths->getPath($baseDir, $userInput);

// Bad - vulnerable to path traversal
$filePath = $baseDir . '/' . $userInput;

function loadUserFile(Paths $paths, string $filename)
{
    // Validate filename
    if (!preg_match('/^[a-zA-Z0-9_-]+\.txt$/', $filename)) {
        throw new InvalidArgumentException('Invalid filename');
    }
    
    // Use secure path joining
    $filePath = $paths->getPath($paths->uploads(), $filename);
    
    return file_get_contents($filePath);
}

// These will throw InvalidArgumentException
$paths->getPath('/safe/dir', '../../../etc/passwd');
$paths->getPath('/safe/dir', '~/sensitive/file');
$paths->getPath('/safe/dir', 'file/../../../etc/passwd');

use PHPUnit\Framework\TestCase;
use ResponsiveSk\Slim4Paths\Paths;

class PathsTest extends TestCase
{
    public function testSecurePathJoining()
    {
        $paths = new Paths('/project', ['uploads' => '/project/uploads']);
        
        // Valid path
        $validPath = $paths->getPath($paths->uploads(), 'file.txt');
        $this->assertEquals('/project/uploads/file.txt', $validPath);
        
        // Invalid path should throw exception
        $this->expectException(InvalidArgumentException::class);
        $paths->getPath($paths->uploads(), '../../../etc/passwd');
    }
}