2

autocompleter.php

 3 years ago
source link: http://winkyfrown.com/autocompleter.php.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
autocompleter.php
<?php
error_reporting( -1 );
ini_set( 'display_startup_errors', 1 );
ini_set( 'display_errors', 1 );

$library = [
    'words' => __DIR__ . '/short.txt'
];

function echoAndExit( $msg ) {
    echo json_encode( $msg );
    exit;
}

function setup() {
    $mc = new Memcache;
    if ( $mc->pconnect( "127.0.0.1", 11211 ) ) {
        return $mc;
    }
    $msg = error_get_last();
    echoAndExit( "Problem setting up memcache: " . $msg['message'] );
}

function getMCKey( $val ) {
    return "custom-ac-$val";
}

$mc = setup();

if ( isset( $_GET['flush'] ) ) {
    foreach( $library as $key => $value ) {
        $mc->delete( getMCKey( $key ) );
    }
    echoAndExit( "cache flushed" );
}

if ( !isset( $_GET['l'] ) || !isset( $_GET['f'] ) ) {
    echoAndExit( "Please provide l with the pattern and f with the file." );
}

if ( strlen( $_GET['l'] ) < 3 ) {
    return;
}

$pattern=preg_quote( $_GET['l'], '/' );
$file=$_GET['f'];

if ( !isset( $library[ $file ] ) ) {
    echoAndExit( "Invalid file!" );
}

if ( !is_readable( $library[ $file ] ) ) {
    echoAndExit( "Can't read file!" );
}

$mcKey = getMCKey( $file );
$data = $mc->get( $mcKey, MEMCACHE_COMPRESSED );
if( $data === false ) {
    $data = explode( "\n", file_get_contents( $library[ $file ] ) );

    if ( !is_array( $data ) ) {
        $msg = error_get_last();
        echoAndExit( "Error reading file: " . $msg['message'] );
    }

    if ( false === $mc->set( $mcKey, $data, MEMCACHE_COMPRESSED, 300 ) ) {
        $msg = error_get_last();
        echoAndExit( "Error saving to cache: " . $msg['message'] );
    }
}


$ret = [];
array_map(
    function( $val ) use (&$ret) {
        $ret[] = [
            'title' => $val
        ];
    },
    array_filter( $data,
              function ($line) use ($pattern) {
                  if ( preg_match( "/$pattern/i", $line ) === 1 ) {
                      return true;
                  }
                  return false;
              } ) );

echoAndExit( [ 'pfautocomplete' => $ret ] );

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK