<commit_before><?php
namespace Pulsestorm\Pestle\Importer;
use function Pulsestorm\Pestle\Runner\getBaseProjectDir;
use ReflectionFunction;
use ReflectionClass;

function pestle_import($thing_to_import, $as=false)
{     
    $ns_called_from  = getNamespaceCalledFrom();
    $thing_to_import = trim($thing_to_import, '\\');    
    $function = extractFunction($thing_to_import);    
    includeCode($thing_to_import, $function, $ns_called_from);                 
    return true;
}

function extractFunction($function_name)
{
    includeModule($function_name);
    $code = createFunctionForGlobalExport($function_name);
    return $code;
}

function createFunctionForGlobalExport($function_name)
{
    $info = extractFunctionNameAndNamespace($function_name);
    //include in the library
    // $code = '<' . '?php' . "\n" .
    $code = 
    'function ' . $info['short_name'] . '(){
        $args = func_get_args();
        return call_user_func_array(\'\\'.$function_name.'\', $args);
    }';
    return $code;
}

function extractFunctionNameAndNamespace($full)
{
    $full       = strToLower($full);
    $parts      = explode('\\', $full);
    $short_name = array_pop($parts);
    $namespace  = implode('/',$parts);
    
    return [
        'short_name'=>$short_name,
        'namespace' =>$namespace
    ];
}

function includeModule($function_name)
{
    $function_name = strToLower($function_name);
    $parts         = explode('\\', $function_name);
    $short_name    = array_pop($parts);
    $namespace     = implode('/',$parts);
    $file          = $namespace . '/module.php';
    return require_once(getBaseProjectDir() . '/modules/' . $file);
}

function functionCollidesWithPhpGlobalSpace($namespace)
{
    $parts      = explode('\\', $namespace);
    $short_name = array_pop($parts);
    
    $results = in_array($short_name, get_defined_functions()['internal']);
    if($results)
    {
        return $short_name;
    }
    return $results;
}

function includeCodeReflectionStrategy($namespace, $code, $ns_called_from)
{

    $cache_dir  = getCacheDir();
    $parts      = explode('\\', $namespace);
    $short_name = array_pop($parts);

    $code = 
    'use function Pulsestorm\Pestle\Importer\functionRegister;'         . "\n";
    $code .= 'use function Pulsestorm\Pestle\Importer\getNamespaceCalledFromForGenerated;' . "\n";
    $code .= "function $short_name(){"                                     . "\n" . 
    '   $function   = functionRegister(__FUNCTION__, getNamespaceCalledFromForGenerated());'            . "\n" .
    '   $args       = func_get_args();'                           . "\n" .
    '   return (new \ReflectionFunction($function))->invokeArgs($args);' . "\n" .
    '}';    
    
    $full_dir   = $cache_dir    . '/' . str_replace('\\','/',strToLower($namespace));
    $filename   = md5($short_name . $code);
    // $full_path  = $full_dir . '/'  . $filename . '.php'; 
    $full_path  = $cache_dir    . '/reflection-strategy/'  . $filename . '.php'; 
    
    functionRegister($short_name, $ns_called_from, $namespace);

    if(file_exists($full_path))
    {        
        // require_once getModulePathToFullyNamespacedFunction($namespace);
        require_once $full_path;    //require the exported file
        return;
    }
    
    

    if(!is_dir(dirname($full_path)))
    {
        mkdir(dirname($full_path), 0755, true);
    }

    if($short_name = functionCollidesWithPhpGlobalSpace($namespace))
    {
        //export with a pestle_prefix
        $code = replaceFirstInstanceOfFunctionName($code, $short_name);
    }
    
    // echo $full_path,"\n";
          
    if(!file_exists($full_path))
    {        
        //exported as function global function                
        file_put_contents($full_path,
            '<' . '?' . 'php' . "\n" .         
            $code . "\n" .
            '##exported for '      . $namespace . "\n");
    }
            
    require_once $full_path ;        
}

function includeCodeFullExportStrategy($namespace, $code)
{
    $cache_dir = getCacheDir();
    $full_dir  = $cache_dir . '/' . str_replace('\\','/',strToLower($namespace));
    $full_path = $full_dir . '/'  . md5($code) . '.php';    
    
    if(file_exists($full_path))
    {
        require_once $full_path;
        return;
    }
    
    if(!is_dir($full_dir))
    {
        mkdir($full_dir, 0755, true);
    }

    if($short_name = functionCollidesWithPhpGlobalSpace($namespace))
    {
        //export with a pestle_prefix
        $code = replaceFirstInstanceOfFunctionName($code, $short_name);
    }
                        
    //exported as function global function                
    file_put_contents($full_path,
        '<' . '?' . 'php' . "\n" .         
        $code . "\n" .
        '##exported for '      . $namespace . "\n");        
    require_once $full_path; 
}
function includeCode($namespace, $code, $ns_called_from)
{   
    includeCodeReflectionStrategy($namespace, $code, $ns_called_from); 
    // includeCodeFullExportStrategy($namespace, $code); 
}

function functionRegister($short_name,$ns_called_from=false,$namespaced_function=false)
{    
    static $functions=[];
    if(!$namespaced_function) { 
        return $functions[$short_name][$ns_called_from]; 
    }
    
//     echo "Registering `$short_name` as `$namespaced_function` 
// for calls from `$ns_called_from`","\n";
    $functions[$short_name][$ns_called_from] = $namespaced_function;    
}
function replaceFirstInstanceOfFunctionName($code, $short_name)
{
    return str_replace('function ' . $short_name, 
    'function pestle_' . $short_name, $code);    
}

function getCacheDir()
{
    $cache_dir = '/tmp/pestle_cache/' . md5(getBaseProjectDir());
    
    if(!is_dir($cache_dir)){ 
        mkdir($cache_dir, 0755);
    }
    return $cache_dir;
}

function getNamespaceCalledFromForGenerated()
{
    return getNamespaceCalledFrom();
}

function getNamespaceCalledFromRequireOrInclude($item)
{
    if(!array_key_exists('function', $item))
    {
        return null;
    }

    if(!in_array($item['function'], ['include','include_once', 'require','require_once']))
    {
        return null;
    }    
    
    static $cache = [];

    if(array_key_exists($item['file'], $cache))
    {
        return $cache[$item['file']];
    }
    return convertAbsoluteFilePathIntoNamespace($item['file']);
}<commit_msg>Fixing cache dir<commit_after><?php
namespace Pulsestorm\Pestle\Importer;
use function Pulsestorm\Pestle\Runner\getBaseProjectDir;
use ReflectionFunction;
use ReflectionClass;

function pestle_import($thing_to_import, $as=false)
{     
    $ns_called_from  = getNamespaceCalledFrom();
    $thing_to_import = trim($thing_to_import, '\\');    
    $function = extractFunction($thing_to_import);    
    includeCode($thing_to_import, $function, $ns_called_from);                 
    return true;
}

function extractFunction($function_name)
{
    includeModule($function_name);
    $code = createFunctionForGlobalExport($function_name);
    return $code;
}

function createFunctionForGlobalExport($function_name)
{
    $info = extractFunctionNameAndNamespace($function_name);
    //include in the library
    // $code = '<' . '?php' . "\n" .
    $code = 
    'function ' . $info['short_name'] . '(){
        $args = func_get_args();
        return call_user_func_array(\'\\'.$function_name.'\', $args);
    }';
    return $code;
}

function extractFunctionNameAndNamespace($full)
{
    $full       = strToLower($full);
    $parts      = explode('\\', $full);
    $short_name = array_pop($parts);
    $namespace  = implode('/',$parts);
    
    return [
        'short_name'=>$short_name,
        'namespace' =>$namespace
    ];
}

function includeModule($function_name)
{
    $function_name = strToLower($function_name);
    $parts         = explode('\\', $function_name);
    $short_name    = array_pop($parts);
    $namespace     = implode('/',$parts);
    $file          = $namespace . '/module.php';
    return require_once(getBaseProjectDir() . '/modules/' . $file);
}

function functionCollidesWithPhpGlobalSpace($namespace)
{
    $parts      = explode('\\', $namespace);
    $short_name = array_pop($parts);
    
    $results = in_array($short_name, get_defined_functions()['internal']);
    if($results)
    {
        return $short_name;
    }
    return $results;
}

function includeCodeReflectionStrategy($namespace, $code, $ns_called_from)
{

    $cache_dir  = getCacheDir();
    $parts      = explode('\\', $namespace);
    $short_name = array_pop($parts);

    $code = 
    'use function Pulsestorm\Pestle\Importer\functionRegister;'         . "\n";
    $code .= 'use function Pulsestorm\Pestle\Importer\getNamespaceCalledFromForGenerated;' . "\n";
    $code .= "function $short_name(){"                                     . "\n" . 
    '   $function   = functionRegister(__FUNCTION__, getNamespaceCalledFromForGenerated());'            . "\n" .
    '   $args       = func_get_args();'                           . "\n" .
    '   return (new \ReflectionFunction($function))->invokeArgs($args);' . "\n" .
    '}';    
    
    $full_dir   = $cache_dir    . '/' . str_replace('\\','/',strToLower($namespace));
    $filename   = md5($short_name . $code);
    // $full_path  = $full_dir . '/'  . $filename . '.php'; 
    $full_path  = $cache_dir    . '/reflection-strategy/'  . $filename . '.php'; 
    
    functionRegister($short_name, $ns_called_from, $namespace);

    if(file_exists($full_path))
    {        
        // require_once getModulePathToFullyNamespacedFunction($namespace);
        require_once $full_path;    //require the exported file
        return;
    }
    
    

    if(!is_dir(dirname($full_path)))
    {
        mkdir(dirname($full_path), 0755, true);
    }

    if($short_name = functionCollidesWithPhpGlobalSpace($namespace))
    {
        //export with a pestle_prefix
        $code = replaceFirstInstanceOfFunctionName($code, $short_name);
    }
    
    // echo $full_path,"\n";
          
    if(!file_exists($full_path))
    {        
        //exported as function global function                
        file_put_contents($full_path,
            '<' . '?' . 'php' . "\n" .         
            $code . "\n" .
            '##exported for '      . $namespace . "\n");
    }
            
    require_once $full_path ;        
}

function includeCodeFullExportStrategy($namespace, $code)
{
    $cache_dir = getCacheDir();
    $full_dir  = $cache_dir . '/' . str_replace('\\','/',strToLower($namespace));
    $full_path = $full_dir . '/'  . md5($code) . '.php';    
    
    if(file_exists($full_path))
    {
        require_once $full_path;
        return;
    }
    
    if(!is_dir($full_dir))
    {
        mkdir($full_dir, 0755, true);
    }

    if($short_name = functionCollidesWithPhpGlobalSpace($namespace))
    {
        //export with a pestle_prefix
        $code = replaceFirstInstanceOfFunctionName($code, $short_name);
    }
                        
    //exported as function global function                
    file_put_contents($full_path,
        '<' . '?' . 'php' . "\n" .         
        $code . "\n" .
        '##exported for '      . $namespace . "\n");        
    require_once $full_path; 
}
function includeCode($namespace, $code, $ns_called_from)
{   
    includeCodeReflectionStrategy($namespace, $code, $ns_called_from); 
    // includeCodeFullExportStrategy($namespace, $code); 
}

function functionRegister($short_name,$ns_called_from=false,$namespaced_function=false)
{    
    static $functions=[];
    if(!$namespaced_function) { 
        return $functions[$short_name][$ns_called_from]; 
    }
    
//     echo "Registering `$short_name` as `$namespaced_function` 
// for calls from `$ns_called_from`","\n";
    $functions[$short_name][$ns_called_from] = $namespaced_function;    
}
function replaceFirstInstanceOfFunctionName($code, $short_name)
{
    return str_replace('function ' . $short_name, 
    'function pestle_' . $short_name, $code);    
}

function getCacheDir()
{
    $cache_dir = '/tmp/pestle_cache/' . md5(getBaseProjectDir());
    
    if(!is_dir($cache_dir)){ 
        mkdir($cache_dir, 0755, true);
    }
    return $cache_dir;
}

function getNamespaceCalledFromForGenerated()
{
    return getNamespaceCalledFrom();
}

function getNamespaceCalledFromRequireOrInclude($item)
{
    if(!array_key_exists('function', $item))
    {
        return null;
    }

    if(!in_array($item['function'], ['include','include_once', 'require','require_once']))
    {
        return null;
    }    
    
    static $cache = [];

    if(array_key_exists($item['file'], $cache))
    {
        return $cache[$item['file']];
    }
    return convertAbsoluteFilePathIntoNamespace($item['file']);
}
{'fraction_non_alphanumeric': 0.15051481568812386, 'fraction_numerical': 0.002357934449422306, 'mean_word_length': 2.6354285714285712, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2264675', 'n_tokens_mistral': 4058, 'n_tokens_neox': 3990, 'n_words': 625}