示例#1
0
 /**
  * Execute the command.
  *
  * @param  InputInterface  $input
  * @param  OutputInterface $output
  *
  * @return void
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $baseDir = $input->getArgument('base');
     if ($baseDir === null) {
         $baseDir = $this->_projectBase;
     }
     $baseDir = rtrim($baseDir, '/') . '/';
     $extensions = AssetResponse::getExtensions();
     $pattern = '*.' . implode(',*.', $extensions);
     $fileList = $this->globRecursive($baseDir . '{' . $pattern . '}', GLOB_BRACE);
     $hashMap = [];
     $data = '';
     foreach ($fileList as $file) {
         $key = str_replace($baseDir, '', $file);
         $hash = ResourceGenerator::getFileHash($file);
         $hashMap[$key] = $hash;
         $data .= "{$key} = {$hash}\n";
     }
     $outputFile = $input->getOption('output');
     $filename = Path::build($baseDir, $outputFile);
     if (!file_exists($filename) || is_writable($filename)) {
         file_put_contents($filename, $data);
         $output->writeln("Written " . count($fileList) . " file hash keys to " . $filename);
     } else {
         $output->writeln("Failed writing to {$filename}");
     }
 }
示例#2
0
 public function testGetSet()
 {
     $view = $this->getMockForAbstractClass('\\Cubex\\View\\ViewModel');
     /**
      * @var $view \Cubex\View\ViewModel
      */
     $view->setTemplateDir('randomDir');
     $this->assertEquals('randomDir', $view->getTemplateDir());
     $view->setTemplateFile('randomFile');
     $this->assertEquals('randomFile', $view->getTemplateFile());
     $this->assertEquals(Path::build('randomDir', 'randomFile.phtml'), $view->getTemplatePath('.phtml'));
 }
示例#3
0
文件: Phid.php 项目: packaged/dal
 public static function generate($object, $append = null, $prefix = null, $moreEntropy = false)
 {
     if ($prefix === null) {
         $class = Objects::classShortname($object);
         $short = self::getUppers($class);
         $prefix = strlen($short) > 1 ? $short : substr(strtoupper($class), 0, 3);
     }
     if ($append !== null) {
         $append = self::getUppers($append);
     }
     return uniqid(Path::buildCustom(':', [$prefix, 'PHID', $append]) . ':', $moreEntropy);
 }
示例#4
0
 protected function setUp()
 {
     $dbgz = 'http://geolite.maxmind.com/download/' . 'geoip/database/GeoLite2-City.mmdb.gz';
     $filename = Path::build(sys_get_temp_dir(), 'GeoLite2-City.mmdb.gz');
     $this->_geoipdb = substr($filename, 0, -3);
     if (!file_exists($this->_geoipdb)) {
         $opts = ['http' => ['method' => "GET", 'header' => "Accept-language: en\r\n" . "User-Agent: CURL (Cubex Framework; en-us)\r\n"]];
         $context = stream_context_create($opts);
         file_put_contents($filename, file_get_contents($dbgz, false, $context));
         $file = gzopen($filename, 'rb');
         $out = fopen($this->_geoipdb, 'wb');
         while (!gzeof($file)) {
             fwrite($out, gzread($file, 4096));
         }
         fclose($out);
         gzclose($file);
         unlink($filename);
     }
 }
示例#5
0
 public function testConfigurations()
 {
     $connectionConfig = new \Packaged\Config\Provider\Ini\IniConfigProvider(Path::build(__DIR__, 'resources', 'connections.ini'));
     $datastoreConfig = new \Packaged\Config\Provider\Ini\IniConfigProvider(Path::build(__DIR__, 'resources', 'datastores.ini'));
     $resolver = new \Packaged\Dal\DalResolver($connectionConfig, $datastoreConfig);
     $this->assertFalse($resolver->hasConnection('conX'));
     $this->assertTrue($resolver->hasConnection('con1'));
     $this->assertFalse($resolver->hasDatastore('ds2'));
     $this->assertFalse($resolver->hasDatastore('ds1'));
     $this->assertTrue($resolver->hasDatastore('qlds'));
     $this->assertTrue($resolver->hasDatastore('filesystem'));
     $connection = $resolver->getConnection('con1');
     /**
      * @var $connection ConfigurableConnection
      */
     $this->assertEquals('Connection Test', $connection->getConfig()->getItem('name'));
     $this->setExpectedException('\\Packaged\\Dal\\Exceptions\\DalResolver\\ConnectionNotFoundException');
     $resolver->getConnection('con2');
 }
示例#6
0
 /**
  * @param ApiPayloadInterface $payload
  * @param null                $path
  * @param null                $verb
  *
  * @return ApiRequest
  */
 protected function _createRequest(ApiPayloadInterface $payload = null, $path = null, $verb = null)
 {
     if ($path === null) {
         $path = $this->_path;
     } else {
         if (substr($path, 0, 1) !== '/') {
             $path = Path::buildUnix($this->_path, $path);
         }
     }
     $path = $this->_buildPath($path, $payload);
     if ($payload === null) {
         $request = ApiRequest::create($verb ? $verb : HttpVerb::GET, $path);
     } else {
         if ($verb === HttpVerb::GET) {
             $request = ApiRequest::create(HttpVerb::GET, $path, [], $payload->toArray());
         } else {
             $request = ApiRequest::create($verb ?: HttpVerb::POST, $path, $payload->toArray());
         }
     }
     $request->setApi($this->getApi());
     return $request;
 }
示例#7
0
 public function testExceptionMissingFile()
 {
     $this->setExpectedException('\\Packaged\\Dal\\Exceptions\\DataStore\\DaoNotFoundException');
     $file = new FileSystemDao(Path::build(dirname(dirname(__DIR__)), 'missing.file'));
     $file->load();
 }
示例#8
0
 /**
  * @param ApiRequestInterface $request
  *
  * @return \GuzzleHttp\Message\RequestInterface
  */
 protected function _createRequest(ApiRequestInterface $request)
 {
     return $this->_getClient()->createRequest($request->getVerb(), Path::buildUnix($this->getUrl(), $request->getPath()) . $request->getQueryString(), $this->_makeOptions($request));
 }
 /**
  * Dispatch a nested URL
  *
  * @param $uri
  *
  * @return string
  */
 protected function _dispatchNestedUrl($uri)
 {
     // if url path is empty, return unchanged
     if (empty($uri[1])) {
         return $uri[0];
     }
     $prefix = '';
     list($path, $append) = Strings::explode('?', $uri[1], [$uri[1], null], 2);
     //Take a root link as it comes
     if (!Strings::startsWith($path, '/')) {
         $relPath = $this->_assetManager->getRelativePath();
         if (Strings::startsWith($path, '../')) {
             $max = count($relPath);
             $depth = substr_count($path, '../');
             $path = substr($path, $depth * 3);
             if ($depth > 0 && $depth < $max) {
                 $rel = array_slice($relPath, 0, $depth);
                 $prefix = implode('/', $rel);
             }
         } else {
             $prefix = implode('/', $relPath);
         }
     }
     $path = ltrim($path, '/');
     $url = $this->_assetManager->getResourceUri(Path::buildUnix($prefix, $path));
     if (empty($url)) {
         return $uri[0];
     }
     if (!empty($append)) {
         return "url('{$url}?{$append}')";
     }
     return "url('{$url}')";
 }
示例#10
0
 protected function _buildUrl($path)
 {
     if ($this->_baseUrl === null) {
         $schemas = $this->_definition->getSchemas();
         rsort($schemas);
         $this->_baseUrl = reset($schemas) . '://';
         $this->_baseUrl .= $this->_definition->getHost();
         $this->_baseUrl .= '/' . ltrim($this->_definition->getBasePath(), '/');
     }
     return Path::buildUnix($this->_baseUrl, $path);
 }
示例#11
0
 public function testBuildCustomPath()
 {
     $this->assertEquals("a|b", Path::buildCustom("|", ["a", "b"]));
     $this->assertEquals("a|b", Path::buildCustom("|", [0 => "a", 1 => "b"]));
 }
示例#12
0
 /**
  * Get the full path to the template file for this viewmodel
  *
  * @param string $extension
  *
  * @return string
  */
 public function getTemplatePath($extension = '.phtml')
 {
     return Path::build($this->getTemplateDir(), $this->getTemplateFile()) . $extension;
 }
示例#13
0
 public static function fromFid($org, $fid, $size = 30)
 {
     return Path::buildUnix('https://storage.googleapis.com/cdn.fortifi.co', $org, 'avatar', $fid . $size . '.png');
 }
示例#14
0
 /**
  * Create the response for the given path
  *
  * @param         $path
  * @param Request $request
  *
  * @return Response
  */
 public function getResponseForPath($path, Request $request)
 {
     if (empty($path)) {
         //What resources do you expect to find with no path?
         return $this->invalidUrlResponse();
     }
     $pathInfo = pathinfo($path);
     //Every dispatch request needs an extension
     if (empty($pathInfo['extension'])) {
         return $this->invalidUrlResponse();
     }
     $response = new AssetResponse();
     //Grab the correct asset for the requesting extension
     $asset = $response->assetByExtension($pathInfo['extension']);
     //Load the options
     $options = ValueAs::arr($this->_config->getItem($pathInfo['extension'] . '_config'), null);
     if ($options !== null) {
         $asset->setOptions($options);
     }
     //Lookup the full path on the filesystem
     $dirMapper = new DirectoryMapper($this->_baseDirectory, $this->_config);
     $directory = $dirMapper->urlToPath($pathInfo['dirname']);
     $filePath = Path::build($directory, $pathInfo['basename']);
     //Do not minify files ending in .min.ext
     if (substr($pathInfo['filename'], -4) == '.min') {
         $asset->setOption('minify', false);
     }
     //If the asset does not exist on disk, return a not found error
     if ($directory === null || !file_exists($filePath)) {
         return $this->notFoundResponse($path);
     }
     //Give the asset its file content
     $asset->setContent(file_get_contents($filePath));
     if ($asset instanceof IDispatchableAsset) {
         //Set the asset manager
         $asset->setWorkingDirectory(realpath($directory));
         $asset->setAssetManager(AssetManager::buildFromUri($path));
     }
     //Create and return the response
     return $response->createResponse($asset, $request);
 }
示例#15
0
 /**
  * Go on the filesystem search for the matching directory
  *
  * @param $base
  * @param $hash
  *
  * @return null
  */
 public function findPathFromHash($base, $hash)
 {
     //If the requesting path is the base, return the base
     if ($hash === 'b') {
         return $base;
     }
     //Attempt to load the resource from disk
     if (isset(static::$_pathCache[func_get_arg(0) . $hash])) {
         return static::$_pathCache[func_get_arg(0) . $hash];
     }
     $hashParts = explode(';', $hash);
     foreach ($hashParts as $part) {
         //Search for directories matching the hash
         $dirs = glob(Path::build($base, substr($part, 0, 2) . '*'), GLOB_ONLYDIR);
         if (!$dirs) {
             return null;
         }
         //If we only found one folder, lets assume its correct
         if (!isset($dirs[1])) {
             $base = $dirs[0];
             continue;
         }
         //Marker to ensure a valid directory has been located
         $found = false;
         //Loop over the directories to match the path
         foreach ($dirs as $path) {
             $folder = [substr($path, strlen($base) + 1)];
             if ($part == $this->hashDirectoryArray($folder, strlen($part) - 2)) {
                 $base = $path;
                 $found = true;
                 break;
             }
         }
         //The directory could not be found, so just give up
         if (!$found) {
             return null;
         }
     }
     //Cache the path to stop future lookups on disk
     $this->cachePath(func_get_arg(0), $hash, $base);
     //Path finally matched
     return $base;
 }
示例#16
0
 protected function _getResourceLocation($filename)
 {
     return Path::build(dirname(__DIR__), 'resources', 'FileSystem', $filename);
 }
use Packaged\Helpers\Strings;
$output = '<?php
namespace Fortifi\\FortifiApi\\ActivityFeed\\Enums;

class ActivityFeedStoryEnum
{
  public static $storyTypes = [
';
$stories = Path::globRecursive(Path::build(__DIR__, 'Stories'));
foreach ($stories as $story) {
    $story = str_replace(__DIR__ . '/Stories/', '', $story);
    //Skip Abstracts and Non Story Classes
    if (Strings::startsWithAny($story, ['Abstract']) || !Strings::endsWith($story, 'Story.php')) {
        continue;
    }
    $part = explode('/', $story);
    $storyClass = array_pop($part);
    $storyClass = str_replace('Story.php', '', $storyClass);
    $storyNs = 'Fortifi\\FortifiApi\\ActivityFeed\\Stories\\' . implode('\\', $part);
    $key = Strings::stringToUnderScore($storyClass);
    //Skip Interfaces
    if (substr($key, 0, 2) == 'i_') {
        continue;
    }
    $output .= "    '{$key}' => '" . $storyNs . "\\" . $storyClass . "Story',\n";
}
$output .= '  ];
}
';
file_put_contents(Path::build(__DIR__, 'Enums', 'ActivityFeedStoryEnum.php'), $output);
示例#18
0
文件: Cubex.php 项目: cubex/framework
 /**
  * @param Request $request
  * @param int     $type
  * @param bool    $catch
  *
  * @return CubexResponse|BinaryFileResponse|Response
  * @throws \Exception
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     //If the favicon has not been picked up within the public folder
     //return the cubex favicon
     if ($request->getRequestUri() === '/favicon.ico') {
         $favIconPaths = [];
         $favIconPaths[] = Path::build($this->getProjectRoot(), 'favicon.ico');
         $favIconPaths[] = Path::build($this->getProjectRoot(), 'assets', 'favicon.ico');
         $favIconPaths[] = Path::build(dirname(__DIR__), 'favicon.ico');
         $favPath = null;
         foreach ($favIconPaths as $favPath) {
             if (file_exists($favPath)) {
                 break;
             }
         }
         $favicon = new BinaryFileResponse($favPath);
         $favicon->prepare($request);
         return $favicon;
     }
     try {
         //Ensure all constants have been configured
         if ($this->getDocRoot() === null) {
             throw new \RuntimeException("Cubex has been constructed without a document root provided" . ", you must call createConstants before calling handle.");
         }
         //Ensure we are working with a Cubex Request for added functionality
         if (!$request instanceof CubexRequest) {
             throw new \InvalidArgumentException('You must use a \\Cubex\\Http\\Request');
         }
         $this->instance('request', $request);
         //Boot Cubex
         $this->boot();
         //Retrieve the
         $kernel = $this->makeWithCubex('\\Cubex\\Kernel\\CubexKernel');
         if ($kernel instanceof CubexKernel) {
             $response = $kernel->handle($request, $type, $catch);
             if (!$response instanceof Response) {
                 throw CubexException::debugException("A valid response was not generated by the default kernel", 500, $response);
             }
             return $response;
         }
         throw new \RuntimeException("No Cubex Kernel has been configured");
     } catch (\Exception $e) {
         if ($catch) {
             return $this->exceptionResponse($e);
         } else {
             throw $e;
         }
     }
 }
示例#19
0
 protected function ownFile()
 {
     return dirname(__DIR__) . DIRECTORY_SEPARATOR . Path::build('vendor', 'packaged', 'dispatch', 'src', 'AssetManager.php');
 }
示例#20
0
 /**
  * Generate the URI for the provided details
  *
  * @param $type
  * @param $lookup
  * @param $domain
  * @param $path
  * @param $file
  *
  * @return null|string
  */
 public function generateUriPath($type, $lookup, $domain, $path, $file)
 {
     $parts = [];
     //Include the map type
     $parts[] = $type;
     //When lookup parts are avilable, e.g. vendor/package, include them
     if (is_array($lookup)) {
         foreach ($lookup as $lookupPart) {
             $parts[] = $lookupPart;
         }
     }
     $parts[] = static::hashDomain($domain);
     //If not path is available, assume you are requesting the base path
     if (empty($path)) {
         $partHash = 'b';
     } else {
         //Build the hashable path
         $partHash = $this->_mapper->hashDirectoryArray(ValueAs::arr(explode('/', $path)));
     }
     $parts[] = $partHash;
     $baseDir = $this->getBasePath($this->_mapper, $type, (array) $lookup);
     $filePath = Path::build($baseDir, $path, $file);
     $fileHash = $this->_dispatcher->getFileHash($filePath);
     if ($fileHash === null) {
         //File hash doesnt exist in the cache, so lets look it up
         $fullPath = Path::build($this->_dispatcher->getBaseDirectory(), $filePath);
         $fileHash = ResourceGenerator::getFileHash($fullPath);
         if (!$fileHash) {
             //If we cant get a hash of the file, its unlikely it exists
             return null;
         }
         //Cache the entry, to optimise should the same resource be re-requested
         $this->_dispatcher->addFileHashEntry($filePath, $fileHash);
     }
     $parts[] = substr($fileHash, 0, 7);
     //Include the file extension
     $parts[] = $file;
     return implode('/', $parts);
 }
示例#21
0
 /**
  * Create a temporary filename
  *
  * @param $key
  *
  * @return string
  */
 private function _createFileName($key)
 {
     return Path::build(sys_get_temp_dir(), 'Fortifi-API-Token-' . $key);
 }
示例#22
0
 /**
  * Execute a route and attempt to generate a response
  *
  * @param IRoute  $route
  * @param Request $request
  * @param int     $type
  * @param bool    $catch
  *
  * @return CubexResponse|null|Response
  * @throws \Exception
  */
 public function executeRoute(IRoute $route, Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     $value = $route->getValue();
     $this->_processParams = $params = $route->getRouteData();
     //If the action has returned a valid response, lets send that back
     if ($value instanceof Response) {
         return $value;
     }
     //Attempt to see if the route is a callable
     if (is_callable($value)) {
         $value = $this->_getCallableResult($value, $params);
     } else {
         if (is_scalar($value)) {
             //If is fully qualified class, create class
             $match = '/^(\\\\?[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)+$/';
             if (stripos($value, '\\') !== false && preg_match($match, $value)) {
                 $class = $value;
                 $nsClass = Path::buildWindows(Objects::getNamespace($this), $value);
                 try {
                     if (class_exists($nsClass)) {
                         $value = $this->getCubex()->make($nsClass);
                     } else {
                         $value = $this->getCubex()->make($class);
                     }
                 } catch (\Exception $e) {
                     if (!$catch) {
                         throw new \RuntimeException("Your route provides an invalid class '{$class}'");
                     } else {
                         return null;
                     }
                 }
             } else {
                 $call = $this->attemptCallable($value);
                 if ($call !== null) {
                     $value = $this->_getCallableResult($call, $params);
                 } else {
                     //Attempt to see if the route is a redirect
                     $url = $this->attemptUrl($value, $request);
                     if ($url !== null) {
                         //Redirect to url
                         return new RedirectResponse($url['url'], $url['code']);
                     } else {
                         //look for method names
                         $method = $this->attemptMethod($value, $request);
                         if ($method !== null) {
                             $value = $this->_getCallableResult([$this, $method], $params);
                         }
                     }
                 }
             }
         }
     }
     if ($value instanceof CubexKernel) {
         $value->_pathProcessed = Path::buildUnix($this->_pathProcessed, $route->getMatchedPath());
         $value->_processParams = $params;
     }
     return $this->_processResponse($value, $request, $type, $catch, $params);
 }
示例#23
0
 /**
  * Match all files within a directory to a pattern recursive
  *
  * @param     $baseDir
  * @param     $pattern
  * @param int $flags
  *
  * @return array
  *
  * @deprecated
  */
 function glob_recursive($baseDir, $pattern = '*', $flags = 0)
 {
     return \Packaged\Helpers\Path::globRecursive($baseDir, $pattern, $flags);
 }
示例#24
0
 /**
  * @param AccessToken $token
  *
  * @return string
  */
 public function urlLogout(AccessToken $token)
 {
     return Path::buildUnix($this->_url, 'auth', 'logout') . '?access_token=' . $token->accessToken;
 }