作者:joussi
项目:framewor
/**
* @param $route_alias
* @param $args
* @return string
*/
public function url($route_alias, $args = array())
{
$routes = $this->router->getRoutes();
$context = new RequestContext(self::getAssetDirectory());
$generator = new UrlGenerator($routes, $context);
return $generator->generate($route_alias, $args);
}
作者:saxulu
项目:saxulum-route-controller-provide
/**
* @Route("/url/{route}", bind="url", values={"route"=null})
*/
public function urlAction($route)
{
if (null === $route) {
$route = 'hello_name';
}
return $this->urlGenerator->generate($route, array('name' => 'urs'), UrlGeneratorInterface::ABSOLUTE_URL);
}
作者:j7mb
项目:silex-auth-skeleto
public function loginAction(Request $req, Twig_Environment $twig, SecurityContext $sc, UrlGenerator $urlgen)
{
if ($sc->isGranted('IS_AUTHENTICATED_FULLY')) {
return new RedirectResponse($urlgen->generate('home'));
} else {
$session = $req->getSession();
$errorConst = $sc::AUTHENTICATION_ERROR;
$lastUsernameConst = $sc::LAST_USERNAME;
return $twig->render('login.html.twig', array('error' => $session->has($errorConst) ? $session->get($errorConst)->getMessage() : null, 'last_username' => $session->get($lastUsernameConst)));
}
}
作者:zyncr
项目:framewor
public function path($routeName, $parameters = array())
{
/** @var Route $route */
$route = $this->routes->get($routeName);
if ($route) {
$context = new RequestContext();
$generator = new UrlGenerator($this->routes, $context);
return $generator->generate($routeName, $parameters);
}
return '';
}
作者:nexher
项目:muffi
public static function generateURI($tag, $args = NULL)
{
$request = Request::createFromGlobals();
$locator = new FileLocator(array(__DIR__));
$loader = new YamlFileLoader($locator);
$routes = $loader->load('../config/routes.yml');
$context = new RequestContext($request->getBaseUrl());
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate($tag);
return $url;
}
作者:BRS-softwar
项目:HearsayRequireJSBundl
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
$container->setParameter('hearsay_require_js.require_js_src', $config['require_js_src']);
$container->setParameter('hearsay_require_js.initialize_template', $config['initialize_template']);
$container->setParameter('hearsay_require_js.base_url', $config['base_url']);
$container->setParameter('hearsay_require_js.base_dir', $this->getRealPath($config['base_dir'], $container));
// Add the base directory as an empty namespace
$config['paths'][''] = array('location' => $config['base_dir'], 'external' => false);
$hideUnoptimizedAssets = !isset($config['optimizer']['hide_unoptimized_assets']) ? false : $config['optimizer']['hide_unoptimized_assets'];
// By using this flag as true, defines will be declared as their module names
$declareModuleName = !isset($config['optimizer']['declare_module_name']) ? false : $config['optimizer']['declare_module_name'];
$container->setParameter('hearsay_require_js.declare_module_name', $declareModuleName);
foreach ($config['paths'] as $path => $settings) {
$location = $settings['location'];
if ($settings['external']) {
$this->addExternalNamespaceMapping($location, $path, $container);
} else {
is_array($location) && ($location = array_shift($location));
$this->addNamespaceMapping($location, $path, $container, !$hideUnoptimizedAssets);
}
}
$container->setParameter('hearsay_require_js.shim', $config['shim']);
$configurationBuilder = $container->getDefinition('hearsay_require_js.configuration_builder');
foreach ($config['options'] as $option => $settings) {
$configurationBuilder->addMethodCall('addOption', array($option, $settings['value']));
}
if (!isset($config['optimizer'])) {
// If the r.js optimizer config isn't provided, don't provide the Assetic filter
$container->removeDefinition('hearsay_require_js.optimizer_filter');
} else {
$container->setParameter('hearsay_require_js.r.path', $this->getRealPath($config['optimizer']['path'], $container));
$filter = $container->getDefinition('hearsay_require_js.optimizer_filter');
if ($config['optimizer']['almond_path']) {
// Makes almond path relative to base directory for r.js optimization
$almondPath = UrlGenerator::getRelativePath($container->getParameter('hearsay_require_js.base_dir'), $this->getRealPath($config['optimizer']['almond_path'], $container));
// Removes file extension if it exists
$almondPath = preg_replace('/\\.js$/', '', $almondPath);
$filter->addMethodCall('setAlmondPath', array($almondPath));
$configurationBuilder->addMethodCall('setUseAlmond', array(true));
}
$filter->addMethodCall('setShim', array($config['shim']));
$filter->addMethodCall('setTimeout', array($config['optimizer']['timeout']));
foreach ($config['optimizer']['exclude'] as $exclude) {
$filter->addMethodCall('addExclude', array($exclude));
}
foreach ($config['optimizer']['modules'] as $name => $module) {
$filter->addMethodCall('addModule', array($name, $module));
}
foreach ($config['optimizer']['options'] as $name => $settings) {
$filter->addMethodCall('addOption', array($name, $settings['value']));
}
}
}
作者:velikano
项目:TubeCrawlerExampleApplicatio
public function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$tubeManipulator = $container->get('velikan_tube_crawler.tube_manipulator');
$tubes = [];
if ($tubeId = $input->hasArgument('tube-id')) {
$tubes[] = $tubeManipulator->find($tubeId);
} else {
$tubes = $tubeManipulator->findAll();
}
$uriFetchAdapter = $container->get('velikan_tube_crawler.uri_fetch_adapter');
$parsedVideoCounter = 0;
$videoParser = $container->get('velikan_tube_crawler.video_parser');
/** @var Tube $tube */
$tube = null;
$fetchAdapterFunction = function ($responseBody, $pageIndex) use(&$tube, $tubeManipulator, $videoParser, $output, &$parsedVideoCounter) {
$videos = $videoParser->parse($responseBody, $tube->getVideoBlockSelector(), $tube->getVideoUriSelector(), $tube->getVideoImageSelector(), $tube->getVideoTitleSelector());
foreach ($videos as $parsedVideo) {
$video = new Video();
$video->setTube($tube);
$video->setVideoUri($parsedVideo['uri']);
$video->setImageUri($parsedVideo['image']);
$video->setTitle($parsedVideo['title']);
$tubeManipulator->testAndCreateVideo($video);
}
$parsedVideoCounter += count($videos);
$output->writeln(sprintf('Parsed %d videos for page %d (%d overall)', count($videos), $pageIndex, $parsedVideoCounter));
};
/** @var Tube $tube */
foreach ($tubes as $tube) {
$output->writeln('Fetching videos for <info>' . $tube->getName() . '</info>');
$routeCollection = new RouteCollection();
$routeCollection->add('uri', new Route($tube->getUrn()));
$requestContext = new RequestContext(Tube::$schemeList[$tube->getScheme()] . '://' . $tube->getHost());
$generator = new UrlGenerator($routeCollection, $requestContext);
$startingPageNumber = $tube->getStartingPageNumber();
for ($i = $startingPageNumber; $i < $input->getOption('pages') + $startingPageNumber; $i++) {
$uri = urldecode($generator->generate('uri', ['page' => $i]));
$uriFetchAdapter->addUri($uri);
}
$uriFetchAdapter->fetch($fetchAdapterFunction, $tube->getCanFetchMultithreaded(), $tube->getThreadCount());
}
}
作者:sitegea
项目:sitegea
/**
* @inheritdoc
*/
public function getRouteUrl($route, $parameters = null)
{
// Convert non-array parameters to empty array or single-value array with default parameter name.
if (is_null($parameters)) {
$parameters = array();
} elseif (!is_array($parameters)) {
$parameters = array($this->getDefaultRouteParameterName() => $parameters);
}
// Generate the URL
$configuredRoute = $this->config(sprintf('routes.%s', $route), $route);
// TODO Allow configuration between absolute URL, absolute path, network URL, relative path, and path relative to base
return $this->urlGenerator->generate($configuredRoute, $parameters, UrlGenerator::ABSOLUTE_URL);
}
作者:piotrminkin
项目:routing-bundl
/**
* @param $variables
* @param $defaults
* @param $requirements
* @param $tokens
* @param $parameters
* @param $name
* @param $referenceType
* @param $hostTokens
* @param array $requiredSchemes
* @return null|string
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = [])
{
if (is_object($parameters)) {
$object = $parameters;
$parameters = [];
} elseif (isset($parameters['object']) && is_object($parameters['object'])) {
$object = $parameters['object'];
unset($parameters['object']);
}
if (isset($object)) {
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
$requiredParams = array_diff_key(array_flip($variables), $mergedParams);
$parameters += $this->getParametersFromObject(array_keys($requiredParams), $object);
}
return BaseUrlGenerator::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
}
作者:devtur
项目:silex-localization-bundl
/**
* {@inheritDoc}
* @param $name string
* @param $parameters array
* @param $referenceType boolean|integer
* @see \Symfony\Component\Routing\Generator\UrlGenerator::generate()
*/
public function generate($name, $parameters = array(), $referenceType = false)
{
//Since Symfony 3 dropped compatibility for booleans
//and completely swapped the logic, let's provide our own compatibility layer.
//We only want to touch booleans. Let proper integer-constant calls to go through.
if ($referenceType === true) {
$referenceType = UrlGeneratorInterface::ABSOLUTE_URL;
} else {
if ($referenceType === false) {
$referenceType = UrlGeneratorInterface::ABSOLUTE_PATH;
}
}
$route = $this->routes->get($name);
if ($route instanceof Route) {
$isRouteLocaleAware = strpos($route->getPath(), '{locale}') !== false;
if ($isRouteLocaleAware) {
if (!array_key_exists('locale', $parameters)) {
try {
$parameters['locale'] = $this->getRequest()->getLocale();
} catch (\RuntimeException $e) {
//Not running in a request context.
}
}
} else {
//Route that doesn't take a locale. If one was provided, get rid of it.
//This is necessary, because we put certain systems into single-locale mode
//(and transparently remove {locale} from routes.
//Still, some code passes locales around.. But the routes no longer need it.
//Instead of fixing all these passers so that they don't pass when in single-locale mode,
//we do this transparently here.
//
//Caveat: If someone uses a non-locale-aware route, but wants a `locale` query string,
//(`locale` meaning something possibly-unrelated to this library),
//we would strip it as well and not pass it along.
//This is a known problem. We take over `locale` and don't let people use it when they
//include this library.
unset($parameters['locale']);
}
}
return parent::generate($name, $parameters, $referenceType);
}
作者:Dolondr
项目:rarg
protected function getRouteUrl($name)
{
if (!isset($this->urlGenerator)) {
throw new \Exception("URLGenerator was not set");
}
return $this->urlGenerator->generate($name);
}
作者:rooste
项目:symfon
public function testAbsoluteSecureUrlWithNonStandardPort()
{
$this->routeCollection->add('test', new Route('/testing'));
$this->generator->setContext(array('base_url' => '/app.php', 'method' => 'GET', 'host' => 'localhost', 'port' => 8080, 'is_secure' => true));
$url = $this->generator->generate('test', array(), true);
$this->assertEquals('https://localhost:8080/app.php/testing', $url);
}
作者:cleentfaa
项目:simplr-cor
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof NotInstalledException) {
$response = new RedirectResponse($this->urlGenerator->generate('simplr_install_welcome'));
$event->setResponse($response);
return;
}
}
作者:blendsd
项目:blendengin
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
{
if ($this->locale !== null && !isset($parameters[RouteAttribute::LOCALE])) {
$parameters[RouteAttribute::LOCALE] = $this->locale;
}
return parent::generate($name, $parameters, $referenceType);
}
作者:nmarian
项目:KnpRadBundl
/**
* {@override}
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
{
if (is_object($parameters)) {
$parameters = $this->readObjectParameters($parameters, $variables);
}
return parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute);
}
作者:ossinkin
项目:amazon-s3-clien
public function testListBucket()
{
$this->authorize();
$listUrl = $this->urlGenerator->generate('list', ['bucket' => 'foo']);
$listBuckets = new Result(['Buckets' => [['Name' => 'foo', 'CreationDate' => '2014-08-01T14:00:00.000Z'], ['Name' => 'bar', 'CreationDate' => '2014-07-31T20:30:40.000Z']]]);
$listObjects = new Result(['Contents' => [['Key' => 'baz', 'ETag' => '"' . md5('baz') . '"', 'LastModified' => '2014-09-10T11:12:13.000Z', 'Size' => 1024], ['Key' => 'qux', 'ETag' => '"' . md5('qux') . '"', 'LastModified' => '2014-09-11T21:22:23.000Z', 'Size' => 2048], ['Key' => 'quxx', 'ETag' => '"' . md5('quxx') . '"', 'LastModified' => '2014-09-12T00:00:00.000Z', 'Size' => 512]], 'IsTruncated' => false]);
$this->s3ClientMock->expects($this->once())->method('listBuckets')->willReturn($listBuckets);
$this->s3ClientMock->expects($this->once())->method('listObjects')->willReturn($listObjects);
$crawler = $this->client->request('GET', $listUrl);
$this->assertTrue($this->client->getResponse()->isOk());
// buckets
$list = $crawler->filter('#list-bucket li');
$active = $list->filter('.active');
$this->assertCount(count($listBuckets['Buckets']), $list);
$this->assertCount(1, $active);
$this->assertEquals($list->eq(0), $active);
$urlGenerator = $this->urlGenerator;
$list->each(function (Crawler $bucket, $index) use($urlGenerator, $listBuckets) {
$link = $bucket->filter('a');
$expectedName = $listBuckets['Buckets'][$index]['Name'];
$this->assertEquals($expectedName, $link->text());
$this->assertEquals($urlGenerator->generate('list', ['bucket' => $expectedName]), $link->attr('href'));
});
// objects
$list = $crawler->filter('#list-object tbody tr');
$this->assertCount(count($listObjects['Contents']), $list);
$list->each(function (Crawler $object, $index) use($listObjects) {
$link = $object->filter('td')->eq(0)->filter('a');
$expectedKey = $listObjects['Contents'][$index]['Key'];
$this->assertEquals($expectedKey, $link->text());
$this->assertEquals('http://foo.s3.amazonaws.com/' . $expectedKey, $link->attr('href'));
$this->assertEquals($listObjects['Contents'][$index]['Size'], $object->filter('td')->eq(1)->text());
});
}
作者:raphaelvige
项目:I18nRoutingServiceProvide
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
// determine the most suitable locale to use for route generation
$currentLocale = $this->context->getParameter('_locale');
if (isset($parameters['_locale'])) {
$locale = $parameters['_locale'];
} else {
if ($currentLocale) {
$locale = $currentLocale;
} else {
$locale = 'en';
}
}
try {
if (false !== ($pos = strpos($name, I18nControllerCollection::ROUTING_PREFIX))) {
$name = substr($name, $pos + strlen(I18nControllerCollection::ROUTING_PREFIX));
}
$url = parent::generate($locale . I18nControllerCollection::ROUTING_PREFIX . $name, $parameters, $referenceType);
return $url;
} catch (RouteNotFoundException $ex) {
// fallback to default behavior
}
// use the default behavior if no localized route exists
return parent::generate($name, $parameters, $referenceType);
}
作者:defra9
项目:levecchiecredenze.i
/**
* Get the URL to a named route.
*
* @param string $name
* @param array $parameters
* @param bool $absolute
* @return string
*/
public function route($name, $parameters = array(), $absolute = true)
{
$route = $this->routes->get($name);
if (isset($route) and $this->usingQuickParameters($parameters)) {
$parameters = $this->buildParameterList($route, $parameters);
}
return $this->generator->generate($name, $parameters, $absolute);
}
作者:Opife
项目:Cm
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
$url = parent::generate($name, $parameters, $referenceType);
if (substr($url, -6) == '/index') {
$url = rtrim($url, "index");
}
return $url;
}
作者:elfe
项目:silicon
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
try {
return parent::generate($name, $parameters, $referenceType);
} catch (RouteNotFoundException $e) {
return $this->generator->generate($name, $parameters, $referenceType);
}
}