One Approach to Complying with a "script-src 'self'" Content Security Policy

I recently encountered this error when working with plugin code on an application:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

The cause of the error was inline script code I was using to pass values from the server to the client.

After a bit of research (see the link above), the best solution looked like a little bit of PHP code to create the JavaScript required to pass the values to the client.

The overhead of checking the timestamp and creating the file is minimal, so this code recreates the JavaScript once each day.

<?php

Class CSP {
	const JSFILENAME = 'csp.js';

	static public function cspFilename($dir = __DIR__) {
		return $dir.'/'.self::JSFILENAME;
	}

	static public function cspFileNeedsRebuild($filename) {
		if (!is_file($filename)) {
			return true;
		}
		$fileLastModified = date('z',filemtime($filename));
		$today = date('z');
		return $fileLastModified !== $today;
	}
}

$someValue = 'Some value';
$jsFilename = CSP::cspFilename();
if (CSP::cspFileNeedsRebuild($jsFilename)) {
	$js = 'var someValue = "'.$someValue.'";'.PHP_EOL;
	file_put_contents($jsFilename,$js);
}
echo '<script src="'.$jsFilename.'"></script>'; 

Other solutions I could have used would have been to disable the Content Security Policy, but that's really a stupid approach. There is also nonce and one may code the policy with more complex values.