Skip to content

Instantly share code, notes, and snippets.

@marzocchi
Created July 1, 2011 09:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marzocchi/1058149 to your computer and use it in GitHub Desktop.
Save marzocchi/1058149 to your computer and use it in GitHub Desktop.
Run Symfony apps with Rack (rackup! pow!)
# vim:se filetype=ruby
# vim:se foldlevel=3
#
# Hacks and monkeys to run Symfony 1.4 applications as Rack apps using
# the rack-legacy and rack-rewrite gems.
#
# A couple of rack-rewrite rules take care of handing requests to the
# default front controller (index.php) and a subclass of rack-legacy's
# Php fixes PATH_INFO for Symfony routing.
#
# Got the idea from:
# http://stuff-things.net/2011/05/16/legacy-development-with-pow/
require 'rubygems'
require 'rack'
require 'rack-legacy'
require 'rack-rewrite'
# Your Symfony project web dir
SF_WEB_DIR = File.join Dir.getwd, 'web'
module Rack
module Legacy
class Symfony < Php
# Strip the script name from PATH_INFO, or Symfony won't be able to parse it
def run(env, path)
if env['PATH_INFO'] =~ %r{^/[^\.]+\.php(.*)$}
env.merge!({ 'ORIG_PATH_INFO' => env['PATH_INFO'], 'PATH_INFO' => $1 })
end
super env, path
end
end
# Monkey rack-legacy's error page to detect and use Symfony's error
# pages by dumping stdout to the browser.
class ErrorPage
# Detect a symfony error page by grepping the version information
# in the footer
def symfony_page?
@stdout =~ %r{<p id="footer">\s+symfony v\.\d+}
end
def to_s
return @stdout if symfony_page?
ERB.new(template).result binding
end
end
end
end
use Rack::Rewrite do
# Dispatch any request for "/" to /index.php
rewrite %r{(^/$)}, lambda {|match, rack_env|
return '/index.php' if File.exists? File.join(SF_WEB_DIR, 'index.php')
rack_env['PATH_INFO']
}
# Prepend "/index.php" to any URI not matching an existing file
# and not containing a php script name
rewrite %r{^(?!/[^\.]+\.php)(/.*)$}, lambda { |match, rack_env|
file = File.join SF_WEB_DIR, rack_env['PATH_INFO']
unless File.exists? file
return '/index.php' + rack_env['PATH_INFO'] if File.exists? File.join(SF_WEB_DIR, 'index.php')
end
rack_env['PATH_INFO']
}
end
use Rack::Legacy::Symfony, SF_WEB_DIR
run Rack::File.new SF_WEB_DIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment