use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub type ClassMap = BTreeMap<Vec<u8>, PathBuf>;
pub fn render_classmap_php(map: &ClassMap, root: &Path, vendor_dir: &Path) -> Vec<u8> {
let mut out = Vec::with_capacity(map.len() * 96);
out.extend_from_slice(b"<?php\n\n// autoload_classmap.php @generated by Composer\n\n");
out.extend_from_slice(b"$vendorDir = dirname(__DIR__);\n");
out.extend_from_slice(b"$baseDir = dirname($vendorDir);\n\n");
out.extend_from_slice(b"return array(\n");
for (fqcn, path) in map {
out.extend_from_slice(b" '");
write_escaped_single_quote(&mut out, fqcn);
out.extend_from_slice(b"' => ");
write_path_expr(&mut out, path, root, vendor_dir, PathStyle::Var);
out.extend_from_slice(b",\n");
}
out.extend_from_slice(b");\n");
out
}
pub fn render_static_classmap_body(map: &ClassMap, root: &Path, vendor_dir: &Path) -> Vec<u8> {
let mut out = Vec::with_capacity(map.len() * 96);
for (fqcn, path) in map {
out.extend_from_slice(b" '");
write_escaped_single_quote(&mut out, fqcn);
out.extend_from_slice(b"' => ");
write_path_expr(&mut out, path, root, vendor_dir, PathStyle::DirRelative);
out.extend_from_slice(b",\n");
}
out
}
pub fn replace_static_classmap(existing: &[u8], new_body: &[u8]) -> Result<Vec<u8>> {
let needle: &[u8] = b"public static $classMap = array (";
let start = memchr_find(existing, needle)
.context("autoload_static.php has no $classMap section to replace")?;
let nl_off = memchr::memchr(b'\n', &existing[start..])
.context("malformed $classMap opening line")?;
let after_open = start + nl_off + 1;
let close = if existing[after_open..].starts_with(b" );") {
after_open
} else {
let close_marker: &[u8] = b"\n );";
let close_rel = memchr_find(&existing[after_open..], close_marker)
.context("autoload_static.php $classMap section has no closing ` );`")?;
after_open + close_rel + 1
};
let mut out = Vec::with_capacity(existing.len() - (close - after_open) + new_body.len());
out.extend_from_slice(&existing[..after_open]);
out.extend_from_slice(new_body);
out.extend_from_slice(&existing[close..]);
Ok(out)
}
fn memchr_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
let first = needle[0];
let mut i = 0;
while let Some(pos) = memchr::memchr(first, &haystack[i..]) {
let abs = i + pos;
if abs + needle.len() > haystack.len() {
return None;
}
if &haystack[abs..abs + needle.len()] == needle {
return Some(abs);
}
i = abs + 1;
}
None
}
#[derive(Copy, Clone)]
enum PathStyle {
Var,
DirRelative,
}
fn write_path_expr(
out: &mut Vec<u8>,
path: &Path,
root: &Path,
vendor_dir: &Path,
style: PathStyle,
) {
if let Ok(rel) = path.strip_prefix(vendor_dir) {
let rel = rel.to_string_lossy();
match style {
PathStyle::Var => {
out.extend_from_slice(b"$vendorDir . '/");
out.extend_from_slice(rel.as_bytes());
out.push(b'\'');
}
PathStyle::DirRelative => {
out.extend_from_slice(b"__DIR__ . '/..' . '/");
out.extend_from_slice(rel.as_bytes());
out.push(b'\'');
}
}
} else if let Ok(rel) = path.strip_prefix(root) {
let rel = rel.to_string_lossy();
match style {
PathStyle::Var => {
out.extend_from_slice(b"$baseDir . '/");
out.extend_from_slice(rel.as_bytes());
out.push(b'\'');
}
PathStyle::DirRelative => {
out.extend_from_slice(b"__DIR__ . '/../..' . '/");
out.extend_from_slice(rel.as_bytes());
out.push(b'\'');
}
}
} else {
out.push(b'\'');
write_escaped_single_quote(out, path.to_string_lossy().as_bytes());
out.push(b'\'');
}
}
fn write_escaped_single_quote(out: &mut Vec<u8>, s: &[u8]) {
for &b in s {
match b {
b'\\' => out.extend_from_slice(b"\\\\"),
b'\'' => out.extend_from_slice(b"\\'"),
_ => out.push(b),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn renders_simple_classmap() {
let mut map = ClassMap::new();
map.insert(b"Foo\\Bar".to_vec(), PathBuf::from("/proj/app/Foo/Bar.php"));
let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
assert!(contains(
&s,
b"'Foo\\\\Bar' => $baseDir . '/app/Foo/Bar.php',"
));
assert!(s.starts_with(b"<?php\n\n// autoload_classmap.php @generated by Composer\n\n"));
assert!(s.ends_with(b");\n"));
}
#[test]
fn renders_vendor_path() {
let mut map = ClassMap::new();
map.insert(
b"Vendor\\Cls".to_vec(),
PathBuf::from("/proj/vendor/acme/lib/src/Cls.php"),
);
let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
assert!(contains(&s, b"$vendorDir . '/acme/lib/src/Cls.php'"));
}
#[test]
fn renders_high_byte_class_key_verbatim() {
let mut map = ClassMap::new();
map.insert(
vec![0xa9],
PathBuf::from("/proj/vendor/symfony/cache/Traits/ValueWrapper.php"),
);
let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
assert!(contains(&s, &[b'\'', 0xa9, b'\'', b' ', b'=', b'>']));
}
#[test]
fn replaces_static_classmap() {
let existing: &[u8] = b"<?php\n\
namespace Composer\\Autoload;\n\
class Foo {\n\
\x20\x20\x20\x20public static $files = array(\n\
\x20\x20\x20\x20\x20\x20\x20\x20'a' => 'b',\n\
\x20\x20\x20\x20);\n\n\
\x20\x20\x20\x20public static $classMap = array (\n\
\x20\x20\x20\x20\x20\x20\x20\x20'Old\\\\Class' => 'old.php',\n\
\x20\x20\x20\x20);\n\n\
\x20\x20\x20\x20public static function getInitializer() {}\n\
}\n";
let new_body: &[u8] = b" 'New\\\\Class' => 'new.php',\n";
let out = replace_static_classmap(existing, new_body).unwrap();
let out_str = std::str::from_utf8(&out).unwrap();
assert!(out_str.contains("'New\\\\Class' => 'new.php',"));
assert!(!out_str.contains("'Old\\\\Class'"));
assert!(out_str.contains("public static $files"));
assert!(out_str.contains("getInitializer"));
}
#[test]
fn replaces_static_classmap_preserves_non_utf8_bytes() {
let mut existing: Vec<u8> = b"<?php\n\
class Foo {\n\
\x20\x20\x20\x20public static $files = array(\n\
\x20\x20\x20\x20\x20\x20\x20\x20'".to_vec();
existing.push(0xa9);
existing.extend_from_slice(b"' => 'val',\n\
\x20\x20\x20\x20);\n\n\
\x20\x20\x20\x20public static $classMap = array (\n\
\x20\x20\x20\x20\x20\x20\x20\x20'X' => 'x.php',\n\
\x20\x20\x20\x20);\n\
}\n");
let new_body: &[u8] = b" 'Y' => 'y.php',\n";
let out = replace_static_classmap(&existing, new_body).unwrap();
assert!(out.contains(&0xa9));
assert!(out
.windows(b"'Y' => 'y.php',".len())
.any(|w| w == b"'Y' => 'y.php',"));
}
#[test]
fn escapes_backslash_and_quote() {
let mut out = Vec::new();
write_escaped_single_quote(&mut out, b"Foo\\Bar");
assert_eq!(out, b"Foo\\\\Bar");
let mut out = Vec::new();
write_escaped_single_quote(&mut out, b"it's");
assert_eq!(out, b"it\\'s");
}
}