<?php

namespace Velis\Filesystem;

use Exception;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
trait FilesystemTrait
{
    /**
     * @param string $key
     * @param string $tmpFileName
     * @return bool
     * @throws Exception
     */
    public function upload($key, $tmpFileName)
    {
        $this->write($key, file_get_contents($tmpFileName));
        unlink($tmpFileName);

        return true;
    }


    /**
     * Normalize path
     * @param string $path
     * @return string
     */
    public static function normalizePath($path)
    {
        $tokens = [];
        if (!is_dir($path)) {
            $path = dirname($path);
        }
        $prefix = strpos($path, '/') === 0 ? '/' : '';
        $path = substr($path, strlen($prefix));
        $parts = array_filter(explode('/', $path), 'strlen');
        foreach ($parts as $part) {
            switch ($part) {
                case '.':
                    continue 2;
                case '..':
                    if (0 !== count($tokens)) {
                        array_pop($tokens);
                        continue 2;
                    } elseif (!empty($prefix)) {
                        continue 2;
                    }
                    //no break
                default:
                    $tokens[] = $part;
            }
        }

        return $prefix . implode('/', $tokens) . '/';
    }
}
