0

I have a configuration file which, amongst other things, defines a whole bunch of values and callables. I'm writing a development tool which needs to update some of the definitions in this file. I can't think of a way to do this which isn't just reading the file and writing my string at a certain point defined by a comment within the file.

Imagine my file looks like this:

<?php

$things = [
    'a_thing' => 'some value',
    'callable_thing' => function() {
        return SomeClass();
    }
    // END THINGS
];

I'd like to insert a new array key into this array (the value of which might be any valid option), in alphabetical order. Is this possible, using Reflection maybe? Second best would be to place a specially formatted comment (i.e the "// END THINGS" comment) as a "target" and insert before it, but I can't help but feel that's pretty hacky, and doesn't satisfy the alphabetical requirement.

I'm aware of the implications of self-mutating code. This is a developer tool and would only be used locally to automate common file->create->update tasks when setting up new projects.

1 Answer 1

1

You could use the var_export() function to print the value of a variable in a way that can be evaluated. So you would load the file with include($filename);, and modify the contents of $things. Then you can update the file with:

$contents = '$things = ' . var_export($things, true) . ';';
file_put_contents($filename, $contents);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Close, but I think it's a non-starter. I need to be able to maintain the code within the function closures. A quick test and it returns Closure::__set_state(array()) for the callable_thing. I think I might need to do some nasty regex'ing to achieve this :(
I didn't even notice that you had a function in there. Could you take the functions out of the array, and define them as named functions, and then put function names in the array?
Sadly not. I went with using the comment "marker" and prepending the text before it. Doesn't tick all the boxes, but gets the job done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.