Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Linq;
- using System.Text.RegularExpressions;
- class NamespaceFixer
- {
- private const string PhpDocAttrMatch = "^ *\\* *@(return|var) +(.+)$";
- private const string PhpDocTagEnd = "^ *\\*/";
- private const string PhpDocTagStart = "^ */\\*\\*";
- private const string PhpFileSearchPattern = "*.php";
- private readonly string _path;
- private readonly string _rootNamespace;
- private static void Main(string[] args)
- {
- if (args.Length != 1)
- {
- Console.Out.WriteLine("No directory specified");
- Environment.Exit(0);
- }
- if (!Directory.Exists(args[0]))
- {
- Console.Out.WriteLine("Directory not found: \"" + args[0] + "\"");
- Environment.Exit(0);
- }
- var namespaceFixer = new NamespaceFixer(args[0]);
- namespaceFixer.Run();
- }
- public NamespaceFixer(string path)
- {
- _path = path;
- _rootNamespace = '\\' + GetLastFolderName(path);
- }
- public void Run()
- {
- Console.Out.WriteLine("Processing directory: \"" + _path + "\"");
- Console.Out.WriteLine();
- Recurse(_path, _rootNamespace);
- }
- private static void FixFile(string path, string currentNamespace)
- {
- // Read all lines of the file.
- var lines = File.ReadAllLines(path);
- // Is the loop currently in a PHPDoc block.
- var isPhpDoc = false;
- // Has the contents of the file been changed.
- var isModified = false;
- for (var i = 0; i < lines.Length; i++)
- {
- if (isPhpDoc)
- {
- // Locate the PHPDoc @return statement.
- var match = Regex.Match(lines[i], PhpDocAttrMatch);
- if (match.Success)
- {
- var declaredNamespace = match.Groups[2].Value;
- if (declaredNamespace.StartsWith("Doctrine\\"))
- {
- var returnPrefix = lines[i].Substring(0, match.Groups[2].Index);
- lines[i] = returnPrefix + '\\' + declaredNamespace;
- isModified = true;
- }
- }
- if (Regex.Match(lines[i], PhpDocTagEnd).Success)
- {
- isPhpDoc = false;
- }
- continue;
- }
- isPhpDoc = Regex.Match(lines[i], PhpDocTagStart).Success;
- }
- if (isModified)
- {
- Console.Out.WriteLine("Modified: \"" + path + "\"");
- File.WriteAllText(path, string.Join("\n", lines));
- }
- }
- private static string GetLastFolderName(string path)
- {
- return path.Split('\\').Last();
- }
- private static void Recurse(string path, string currentNamespace)
- {
- foreach (var directory in Directory.GetDirectories(path))
- {
- // Skip SVN directories.
- if (directory.ToLower().EndsWith(".svn"))
- {
- continue;
- }
- Recurse(
- directory,
- currentNamespace + '\\' + GetLastFolderName(directory));
- }
- foreach (var file in Directory.GetFiles(path, PhpFileSearchPattern))
- {
- FixFile(file, currentNamespace);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement