PHP code example of puleeno / rake-wordpress-migration-example

1. Go to this page and download the library: Download puleeno/rake-wordpress-migration-example library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

puleeno / rake-wordpress-migration-example example snippets


// Thay vì viết code thủ công
$data = file_get_contents($url);
$parsed = parseData($data);
saveToDatabase($parsed);

// Sử dụng visual flow composer
// Drag & drop các components
// Auto generate code

// Tích hợp hoàn hảo với WordPress
add_action('wp_ajax_crawlflow_save_project', [$this, 'handleSaveProject']);
add_action('admin_menu', [$this, 'registerMenu']);
add_action('wp_loaded', [$this, 'initialize']);

// Tự động migrate database
$migrationService = new MigrationService();
$result = $migrationService->runMigrations();

// Version tracking
$version = $migrationService->getCurrentVersion();

// WP-CrawlFlow sử dụng Rake Core
use Rake\Rake;
use Rake\Facade\Logger;
use Rake\Manager\Database\MigrationManager;

// WP-CrawlFlow sử dụng Rake WordPress Adapter
use Rake\WordPress\Database\WordPressDatabaseAdapter;
use Rake\WordPress\Hooks\WordPressHooksAdapter;
use Rake\WordPress\Admin\WordPressAdminAdapter;

// Service registration
$app = new Rake();
$app->singleton(DatabaseAdapterInterface::class, WordPressDatabaseAdapter::class);
$app->singleton(WordPressHooksInterface::class, WordPressHooksAdapter::class);
$app->singleton(WordPressAdminInterface::class, WordPressAdminAdapter::class);

// Trong wp-crawlflow.php
class WP_CrawlFlow
{
    private Rake $app;
    private CrawlFlowController $controller;

    public function __construct()
    {
        // Initialize Rake container
        $this->app = new Rake();

        // Register service providers
        $this->app->register(new CrawlFlowCoreServiceProvider());
        $this->app->register(new CrawlFlowDashboardServiceProvider());
        $this->app->register(new CrawlFlowMigrationServiceProvider());

        // Initialize controller
        $this->controller = new CrawlFlowController($this->app);
        $this->controller->registerHooks();
    }
}

// Sử dụng ProjectService
$projectService = new ProjectService();

$project = $projectService->createProject([
    'name' => 'My Crawl Project',
    'description' => 'Crawl data from website',
    'settings' => [
        'url' => 'https://example.com',
        'selectors' => ['h1', 'h2', '.content'],
        'output_format' => 'json'
    ]
]);

// Plugin tự động run migrations khi activate
$migrationService = new MigrationService($app);
$result = $migrationService->runMigrations();

if ($result['success']) {
    Logger::info('Migrations completed successfully');
} else {
    Logger::error('Migration failed: ' . $result['error']);
}

// Run migrations manually
$kernel = new CrawlFlowMigrationKernel($app);
$kernel->runMigrations();

// Check migration status
$status = $kernel->checkMigrationStatus();
echo "Current version: " . $status['current_version'];

use Rake\Facade\Logger;

// Logger chỉ được initialize khi cần
Logger::info('Starting crawl process');
Logger::error('Crawl failed', ['url' => $url, 'error' => $error]);
Logger::debug('Processing data', ['count' => count($data)]);

// PHP Handler
public function handleSaveProject()
{
    if (!wp_verify_nonce($_POST['nonce'], 'crawlflow_save_project')) {
        wp_die('Security check failed');
    }

    $projectService = new ProjectService();
    $result = $projectService->createProject($_POST['project']);

    if ($result) {
        wp_send_json_success(['id' => $result]);
    } else {
        wp_send_json_error('Failed to save project');
    }
}

// Register admin menu
public function registerMenu()
{
    add_menu_page(
        'CrawlFlow',
        'CrawlFlow',
        'manage_options',
        'crawlflow',
        [$this, 'renderProjectsPage'],
        'dashicons-networking',
        30
    );

    add_submenu_page(
        'crawlflow',
        'Projects',
        'Projects',
        'manage_options',
        'crawlflow',
        [$this, 'renderProjectsPage']
    );

    add_submenu_page(
        'crawlflow',
        'Logs',
        'Logs',
        'manage_options',
        'crawlflow-logs',
        [$this, 'renderLogsPage']
    );
}

class CrawlFlowDashboardKernel extends AbstractKernel
{
    private DashboardService $dashboardService;
    private CrawlFlowController $controller;

    public function __construct(Rake $app)
    {
        parent::__construct($app);

        $this->dashboardService = new DashboardService();
        $this->controller = new CrawlFlowController($app);

        $this->detectCurrentScreen();
        $this->loadScreenData();
    }

    public function render(): void
    {
        $this->controller->renderPage();
    }
}

class MigrationService
{
    private Rake $app;
    private WordPressDatabaseAdapter $adapter;

    public function __construct(Rake $app)
    {
        $this->app = $app;
        $this->adapter = new WordPressDatabaseAdapter();
    }

    public function runMigrations(): array
    {
        try {
            $schemaPath = $this->app->get('migration_schema_path');
            $definitions = $this->getSchemaDefinitions($schemaPath);

            foreach ($definitions as $table => $schema) {
                $this->createTable($table, $schema);
            }

            return ['success' => true];
        } catch (Exception $e) {
            Logger::error('Migration failed: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}

class ProjectService
{
    private WordPressDatabaseAdapter $adapter;

    public function createProject(array $data): int
    {
        $data['created_at'] = current_time('mysql');
        $data['updated_at'] = current_time('mysql');

        return $this->adapter->insert('crawlflow_projects', $data);
    }

    public function getProjects(): array
    {
        return $this->adapter->getResults("
            SELECT * FROM {$this->adapter->getPrefix()}crawlflow_projects
            ORDER BY created_at DESC
        ");
    }
}

// Always use WordPress functions with backslash prefix
$result = \wp_verify_nonce($nonce, $action);

// Use WordPress security functions
$sanitized = \sanitize_text_field($input);

// Check capabilities before actions
if (\current_user_can('manage_options')) {
    // Perform admin action
}

// Use WordPress hooks properly
\add_action('init', [$this, 'initialize']);

// Use Rake Facades
use Rake\Facade\Logger;

Logger::info('Operation started');
Logger::error('Operation failed', ['context' => $data]);

// Use Rake Container
$app = new Rake();
$service = $app->make(ServiceInterface::class);

// Use Rake Database Adapter
$adapter = new WordPressDatabaseAdapter();
$result = $adapter->query('SELECT * FROM table');

class CrawlFlowControllerTest extends TestCase
{
    private CrawlFlowController $controller;

    protected function setUp(): void
    {
        $app = new Rake();
        $this->controller = new CrawlFlowController($app);
    }

    public function testSaveProject(): void
    {
        // Arrange
        $projectData = [
            'name' => 'Test Project',
            'description' => 'Test Description'
        ];

        // Act
        $result = $this->controller->handleSaveProject($projectData);

        // Assert
        $this->assertTrue($result['success']);
    }
}

class CrawlFlowIntegrationTest extends TestCase
{
    public function testDashboardRendering(): void
    {
        // Arrange
        $app = new Rake();
        $kernel = new CrawlFlowDashboardKernel($app);

        // Act
        ob_start();
        $kernel->render();
        $output = ob_get_clean();

        // Assert
        $this->assertStringContainsString('CrawlFlow', $output);
    }
}

class CrawlFlowException extends Exception
{
    public function __construct(string $message, array $context = [], int $code = 0, ?Throwable $previous = null)
    {
        parent::__construct("CrawlFlow error: {$message}", $code, $previous);
    }
}

// Usage
try {
    $migrationService = new MigrationService($app);
    $result = $migrationService->runMigrations();
} catch (CrawlFlowException $e) {
    Logger::error('CrawlFlow operation failed: ' . $e->getMessage());
}

// Tự động detect từ WordPress
$adapter = new WordPressDatabaseAdapter();
echo $adapter->getPrefix();        // wp_
echo $adapter->getCharset();       // utf8mb4
echo $adapter->getCollation();     // utf8mb4_unicode_ci

// Logger configuration
add_filter('crawlflow/logger', function($path) {
    return '/custom/path/to/logs/crawlflow.log';
});

// Migration configuration
add_filter('crawlflow/migration_schema_path', function($path) {
    return '/custom/path/to/schemas/';
});

// Ensure WordPress is loaded

// Check database permissions
// Verify WordPress database configuration
// Check migration schema files

// Enable debug mode
define('CRAWFLOW_DEBUG', true);

// Check logs
Logger::debug('Debug information');
Logger::error('Error information');

// Use transactions for multiple operations
$adapter->beginTransaction();
try {
    foreach ($projects as $project) {
        $adapter->insert('crawlflow_projects', $project);
    }
    $adapter->commit();
} catch (Exception $e) {
    $adapter->rollback();
    throw $e;
}

// Use batch operations
$adapter->getResults("SELECT * FROM crawlflow_projects LIMIT 1000");

// Use specific columns
$adapter->getResults("SELECT id, name FROM crawlflow_projects WHERE status = 'active'");

// Initialize plugin
$plugin = new WP_CrawlFlow();

// Use dashboard
// WordPress Admin → CrawlFlow → Projects

// Use visual composer
// Projects → Add New → Visual Flow Composer

// Use migration
$migrationService = new MigrationService($app);
$result = $migrationService->runMigrations();
bash
composer dump-autoload